VivekT
VivekT

Reputation: 81

Why map method does not return array of object?

let x = {a:1,b:2,c:3}
let result = Object.keys(x).map((i) => {
  console.log(i) ;
  return ({i :x[i]});
})

why result is

[{i: 1},{i: 2},{i: 3}]

? In console, value of i i.e a,b,c is being printed. What happens during return?

Upvotes: 0

Views: 77

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075567

Why map method does not return array of object?

It does.

What happens during return?

The return ({i :x[i]}); line means:

  • Create an object.
  • Give it a property called "i" (not the value of i, the actual literal name "i") with the value from x[i].
  • Return that as the value for this map iteration, which will be used in the result array.

The result is an array of objects, each with one property called "i".

If you meant to use the value of i, you'd need to use a computed property name. There's also no reason for the () around the object literal:

return {[i]: x[i]};
//      ^^^------------- computed property name

Live Example:

let x = {a:1,b:2,c:3};
let result = Object.keys(x).map((i) => {
  console.log(i) ;
  return {[i]: x[i]};
});
console.log(result);
.as-console-wrapper {
    max-height: 100% !important;
}

This was introduced in ES2015. In ES5 and earlier, you'd have to create the object first, then add the property to it afterward.

Upvotes: 3

Related Questions