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

How to map JSON Object to array with keys in javascript

There’s about million questions (and answers) out there on this topic, but none of them are doing what I need to do. I have a JSON object where the value for each key is an object. I want to convert this to an array and maintain the top level keys.

{
  "someKey1": {
    active: true,
    name: "foo"
  },
  "someKey2": {
    active: false,
    name: "bar"
  }
}

If I use Object.keys() I get the top level keys, but not their values. If I use Object.values() I get an array with all the values, but not their keys. I’m trying to use keys and map, but am only getting the values returned:

const data = {
  "someKey1": {
    active: true,
    name: "foo"
  },
  "someKey2": {
    active: false,
    name: "bar"
  }
}
const items = Object.keys(data).map(function(key) {
    return data[key];
});

// returns [{active: true, name: foo},{active: false, name: bar}]

Is there a way to get both? I want to get an array I can iterate over that looks something like this:

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

[{
    key: someKey1,
    active: true,
    name: "foo"
},
{
    key: someKey2,
    active: true,
    name: "foo"
}]

OR

[
"someKey1": {
    active: true,
    name: "foo"
},
"someKey2": {
    active: false,
    name: "bar"
}
]

>Solution :

I think you are going in the right direction, if you want to add the "key" property you have to map the properties manually and for the second option since you don’t need the "key" property it can be done a little bit more elegantly:

For the first option:

Object.keys(data).map(v => ({
    key: v,
    ...data[v]
}));

For the second option even simpler:

Object.keys(data).map(v => ({[v]: {...data[v]}}))
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