Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return object from array map

Suppose I could hardcode the following:

const data = [ { a: 0, b: 1}, {a:2,b:3},... ]

But I have the data in an array, and I would like to write something like the following:

const data = my_arr.map((element,index) => { a:element, b:index});

How does one yield this kind of object from an array map?

like image 477
Chris Avatar asked Feb 12 '19 22:02

Chris


People also ask

Can map return an array of objects?

map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array.

How do you return an object to an array?

To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() . Note that the Object.keys() method has been available since ECMAScript 2015 or ES6, and the Object.values() and Object.entries() have been available since ECMAScript 2017.

Does array map need a return?

Inside the function we need to return something. As the map() method calls the function on each item in the array, whatever we return in the function becomes that items value. Therefore if we return person we will get back exactly what we had in the original array.

What does map () return in JavaScript?

Return Value: It returns a new array and elements of arrays are result of callback function.


1 Answers

You just need to add parenthesis around the returned object literal.

const my_arr = [1,2,3,4,5];
const data = my_arr.map((element, index) => ({ a: element, b:index }));
//                                          ^                       ^    

console.log(data);

The reason is that the JavaScript parser rules assume that the { following the => is the start of a function body. To go around this, we wrap the object in () (alternatively we can add a return statement)

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals

like image 69
nem035 Avatar answered Oct 02 '22 11:10

nem035