Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flatten then map object to array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.entries returns 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 map and [animal, { value }] extracts the first string in the individual arrays in animal and since the second one, the value, is an object, we destructure it and get only the value out of it.

  • Object construction

    Now that we have all pieces needed to construct our objects, animal and value, we use the short hand notation to construct objects with { animal, value }. That basically creates an object with the keys animal and value with the values of the actual variables against them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading