Home > Blockchain >  How to map JSON Object to array with keys in javascript
How to map JSON Object to array with keys in javascript

Time:06-05

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:

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

OR

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

CodePudding user response:

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]}}))

CodePudding user response:

You can easily map your data to a new object:

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