I'm learning about fetch()
and am struggling to overcome an issue. I have some JSON data I am fetching, but the key is the "parent" of each item, eg it looks like:
products
p1
description:"Lorem Ipsum"
name:"some product"
price:9.99
p2
description:"Dolar sit amet"
name:"another product"
price:15.5
I'd like to .map()
this data into a new array, as such:
const newData= data.results.map(item => {
return {
id: item.id,
name: item.name,
description: item.description,
price: item.price
};
});
But I don't understand how I can iterate through each item and save it's ID without a key.
Would anyone know how I could do this?
CodePudding user response:
You can do this with Object.entries()
function:
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well.
Object.entries(data.products).map(([key, value]) => ({
id: key,
name: value.name,
description: value.description,
price: value.price
}));
CodePudding user response:
Since what you have posted looks like object, rather than array. You have to first transform it into an array. I would suggest using Object.entries()
Object.entries(products).map(([key, value])=> {
return {
id: key,
name: value.name,
description: value.description,
price: value.price
}
})