简体   繁体   中英

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 ie a,b,c is being printed. What happens during return?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM