I have an object that needs to be mapped into array with the key as a property. The object looks like:
{
Cat: {
value: 50
},
Dog: {
value: 80
}
}
I need to convert this to:
[
{
animal: 'Cat',
value: 50
},
{
animal: 'Dog',
value: 80
}
]
Any help will be greatly appreciated.
I have tried
const animalArr = Object.entries(AnimalObj);
But am unsure on next step.
>Solution :
const AnimalObj = {
Cat: {
value: 50
},
Dog: {
value: 80
}
};
const result = Object.entries(AnimalObj)
.map(([animal, { value }]) => ({ animal, value }));
console.log(result);
Iterate through all the entries of the AnimalObj with Object.entries and construct a new object out of each entry with map.
The map part in the answer might look a bit complicated.
([animal, { value }]) => ({ animal, value })
It actually has two parts,
-
argument destructuring
The
Object.entriesreturns an array of key and its corresponding value as arrays. In your case,console.log(Object.entries(AnimalObj))would have printed[ [ 'Cat', { value: 50 } ], [ 'Dog', { value: 80 } ] ]We pass each and every array in to
mapand[animal, { value }]extracts the first string in the individual arrays inanimaland since the second one, the value, is an object, we destructure it and get only thevalueout of it. -
Object construction
Now that we have all pieces needed to construct our objects,
animalandvalue, we use the short hand notation to construct objects with{ animal, value }. That basically creates an object with the keysanimalandvaluewith the values of the actual variables against them.