从列表生成对象

时间:2019-05-31 13:20:55

标签: ecmascript-6

我有一个像这样的数组:[1, 2, 3, 4, 5],我想从中获得一个像这样的对象:

[
  { product_id: 1 },
  { product_id: 2 },
  { product_id: 3 },
  { product_id: 4 },
  { product_id: 5 }
]

什么是ES6ish方式?

1 个答案:

答案 0 :(得分:1)

问题在于了解ES6 .map()返回如何工作。

在地图上添加圆括号,因为您想返回该语句。花括号只是打开身体,没有返回值。 (您必须自己添加它,例如{ return {product_id: item }}

const inputArr = [1, 2, 3, 4, 5];
const newArr = inputArr.map(item => ({ product_id: item })); 
console.log('arrayLog', newArr);