简体   繁体   中英

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?

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

Ah, figured this out.

The anonymous object clashes with the scope operators, so you need to encapsulate the object in a scope block, and pass the object by return from there:

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

You have to add parenthesis around your returned object to differentiate it from a simple block:

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

Or return it explicitly :

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

I guess it's the same

 var my_arr = [...Array(5).keys()] var result = my_arr.map((element,index) => ({ a: element, b: element + 1 })); console.log('result', result)

So, it works

See output:

 var results = []; [...Array(11).keys()].forEach((el) => { if (el % 2 === 0) { results.push({ a: el, b: el + 1 }) } }) console.log('results',results)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM