简体   繁体   中英

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:

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

OR

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

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

您可以轻松地将数据映射到新对象:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM