admin管理员组

文章数量:1208155

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?

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?

Share Improve this question asked Feb 12, 2019 at 22:16 ChrisChris 31.2k31 gold badges100 silver badges187 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 18

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

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);

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}});

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)

本文标签: javascriptreturn object from array mapStack Overflow