如何将键传递到作为对象的值。我想将作为产品ID级别的键向下移动到值"0";id";
我有一个这样的数组:
const products = [
{
"2": {
"name": "Name of product with id 2",
"ean": "123123123",
"parameters": []
},
"3": {
"name": "Name of product with id 3",
"ean": "123123122",
"parameters": []
},
"5": {
"name": "Name of product with id 5",
"ean": "123123121",
"parameters": []
}
}
]
我期待这个:
[
{
"id": "2",
"name": "Name of product with id 2",
"ean": "123123123",
"parameters": []
},
{
"id": "3",
"name": "Name of product with id 3",
"ean": "123123122",
"parameters": []
},
{
"id": "5",
"name": "Name of product with id 5",
"ean": "123123121",
"parameters": []
}
]
- 使用
Array#flatMap
和Object#entries
,获取id对象对列表 - 使用
Array#map
,迭代上述属性,并将id
添加到其他属性中
const products = [
{
"2": { "name": "Name of product with id 2", "ean": "123123123", "parameters": [] },
"3": { "name": "Name of product with id 3", "ean": "123123122", "parameters": [] },
"5": { "name": "Name of product with id 5", "ean": "123123121", "parameters": [] }
}
];
const res = products
.flatMap(Object.entries)
.map(([ id, props ]) => ({ ...props, id }));
console.log(res);
您可以简单地通过使用Object.keys((和Array.map((方法来实现这一点。
演示:
const products = [
{
"2": {
"name": "Name of product with id 2",
"ean": "123123123",
"parameters": []
},
"3": {
"name": "Name of product with id 3",
"ean": "123123122",
"parameters": []
},
"5": {
"name": "Name of product with id 5",
"ean": "123123121",
"parameters": []
}
}
];
const res = Object.keys(products[0]).map((id) => {
products[0][id]['id'] = id;
return products[0][id];
});
console.log(res);