简体   繁体   中英

Get a sub-object for every object in JSON using Javascript

I have JSON that is a list of county objects with several year sub-objects. The format is like this:

{
county1: {
  "2007": {
    "data1": 5,
    "data2": 58
  },
  "2008": {
    "data1": 12,
    "data2": 63
  },
},

county2: {
  "2007": {
    "data1": 75,
    "data2": 3
  },
  "2008": {
    "data1": 9,
    "data2": 8
  },
}

}

Is there an easy way in javascript to return a similar structure, but with only a single year for each county ie 2008?

Consider your data as data variable and design the way you want your new data to be structured

Object.keys(data).reduce((acc, val) => {
    acc[val] = data[val]['2008']
    return acc;
}, {})

OR

Object.keys(data).reduce((acc, val) => {
    acc[val] = {'2008':  data[val]['2008']}
    return acc;
}, {})

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