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?
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.
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.
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.
Return Value: It returns a new array and elements of arrays are result of callback function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With