Home > database >  Flatten then map object to array
Flatten then map object to array

Time:12-12

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.

CodePudding user response:

const data = {
 Cat: {
   value: 50
 },
 Dog: {
   value: 80
 }
};

const out = Object.entries(data).map(([key, value]) => {
  return {
    animal: key,
    ...value
  };
});

console.log(out);

CodePudding user response:

You don't need to flatten it in a separate step. Just map it directly:

AnimalObj = {
 Cat: {
   value: 50
 },
 Dog: {
   value: 80
 }
} 


 const animalArr = Object.entries(AnimalObj).map(([ key, value ]) => ({ animal: key, value: value.value }));
 console.log(animalArr)

CodePudding user response:

const AnimalObj = {
    Cat: {
        value: 50
    },
    Dog: {
        value: 80
    }
};

console.log(
    Object
       .entries(AnimalObj)
       .map(([animal, { value }]) => ({ animal, value}))
);

Iterate through all the entries of the AnimalObj with Object.entries and construct a new object out of each entry with map.

  • Related