Reputation: 81
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
Reputation: 1075567
Why map method does not return array of object?
It does.
What happens during return?
The return ({i :x[i]});
line means:
"i"
(not the value of i
, the actual literal name "i"
) with the value from x[i]
.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