10

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?

0

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

You could do the same by enclosing the braces with parentheses. .map((element,index) => ({a:element,b:index}))
0

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

Comments

0

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)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.