2

let a = [{num:'1'},{num:'2'}];
let b = ['1','2'];
let c = b.map(i=>{num:i});

console.log(a);
console.log(c);

I expected variable c to be identical to a, which doesn't happen. Why is the Object initializer syntax not allowed as I'm using it?

3
  • 2
    Your object initializer is being treated like a code block. Use parentheses for it to be evaluated as an expression. ({num:i}) Commented Dec 16, 2016 at 22:49
  • 1
    what 4castle said. Furthermore, it's not a problem with map but in general with arrow functions. Commented Dec 16, 2016 at 22:49
  • As a perhaps irrelevant side note. The example initializes a new array with incrementing numbers. The same can be done with let c = Array.from({length:2},(o,i)=>({num:i+1})); (Same goes for parentheses around the arrow function though.) For 2 entries it doesn't matter, but for larger quantities it makes life easier. Likely it was just an example, but thought I'd mention it just in case Commented Dec 16, 2016 at 23:01

1 Answer 1

4

The problem is the classic Javascript one: the contents of your arrow function are being treated as a block, not as a function literal, with num as a label, not as an object key. You need to wrap the literal in brackets () to make it work:

let a = [{num:'1'},{num:'2'}];
let b = ['1','2'];
let c = b.map(i=>({num:i}));

console.log(a);
console.log(c);
Sign up to request clarification or add additional context in comments.

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.