Ecmascript 6 从列表生成对象
我有一个这样的数组:Ecmascript 6 从列表生成对象,ecmascript-6,Ecmascript 6,我有一个这样的数组:[1,2,3,4,5],我想从中获得如下对象: [ { product_id: 1 }, { product_id: 2 }, { product_id: 3 }, { product_id: 4 }, { product_id: 5 } ] 什么是ES6ish方法来获得此结果?问题在于理解ES6.map()返回如何工作 为映射添加圆括号,因为您希望返回该语句。花括号只打开body,没有返回值。(您必须自己添加它,例如{return{product\u
[1,2,3,4,5]
,我想从中获得如下对象:
[
{ product_id: 1 },
{ product_id: 2 },
{ product_id: 3 },
{ product_id: 4 },
{ product_id: 5 }
]
什么是ES6ish方法来获得此结果?问题在于理解ES6.map()返回如何工作 为映射添加圆括号,因为您希望返回该语句。花括号只打开body,没有返回值。(您必须自己添加它,例如
{return{product\u id:item}}
)
constinputarr=[1,2,3,4,5];
const newArr=inputArr.map(item=>({product_id:item}));
console.log('arrayLog',newArr);
您试过什么吗?for
循环,map方法可能?我不想使用循环,因为我想使用ES6功能。for of
是ES6功能。const newArr=arr.map(item=>{product\u id:item;});log(JSON.stringify(newArr))代码>但这给了我一个空对象数组。请参阅