将数组值转换为对象

时间:2021-04-23 09:39:37

标签: javascript node.js

我有这个代码

const jsonArray = [1,2,3,4,5];

我想转换它以便我可以得到

{
 "id" : 1
},
{
 "id" : 2
},
{
 "id" : 3
},
{
 "id" : 4
},
{
 "id" : 5
}

所以我需要为所有对象输出添加“id”键

3 个答案:

答案 0 :(得分:1)

试试地图功能

jsonObjectArray = jsonArray.map((ele) => {return {"id": ele}})

答案 1 :(得分:1)

您可以使用地图。

jsonArray.map(id=>({id}))

答案 2 :(得分:1)

您可以使用 Array.prototype.map()

const jsonArray = [1,2,3,4,5];
        
const arrayofObjects = jsonArray.map(e => ({id: e}))

console.log(arrayofObjects);