how can I transfer a key to a value which is an object. I would like to move key which is the product ID level down to a value as "id"
I have an array like this:
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": []
}
}
]
I am expecting this:
[
{
"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": []
}
]
CodePudding user response:
- Using
Array#flatMap
andObject#entries
, get list of id-object pairs - Using
Array#map
, iterate over the above and addid
to the other properties
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);
CodePudding user response:
You can simply achieve that by using Object.keys() along with Array.map() method.
Demo :
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);