简体   繁体   中英

retrieve data from JSON object in JS

I'm in trouble with a JSON object in JS. I would like to retrieve an array of value for each string, for all objects in a data collection.

for instance, I have

mystuff = [{"item1":"12", "item2":"25", "item3":"16"},
{"item1":"14", "item2":"21", "item3":"18"},
{"item1":"13", "item2":"22", "item3":"17"}]

and I'm looking for

theGoodOne = [{"item1":["12", "14","13"]},
{"item2":["25","21","22"]},
{"item3":["16","18","17"]}]

I believe I have to search around dataframes, but I think my major issue is the bad vocabulary I use to perform a fruitful research.

Thanks a lot !

Here's a basic script that transforms the data structure:

 mystuff = [{"item1":"12", "item2":"25", "item3":"16"}, {"item1":"14", "item2":"21", "item3":"18"}, {"item1":"13", "item2":"22", "item3":"17"}]; var theGoodOne = mystuff.reduce(function(acc, el){ Object.keys(el).forEach(function(k){ if (el.hasOwnProperty(k)) { acc[k] = acc[k] || []; acc[k].push(el[k]); } }); return acc; }, {}); console.log(theGoodOne); 

You can use reduce and Object.values to achieve it.

 let mystuff = [{"item1":"12", "item2":"25", "item3":"16"}, {"item1":"14", "item2":"21", "item3":"18"}, {"item1":"13", "item2":"22", "item3":"17"}]; let theGoodOne = Object.values(mystuff.reduce((c, v) => { for (var k in v) { c[k] = c[k] ? c[k] : {}; c[k][k] = c[k][k] || []; c[k][k].push(v[k]); } return c; }, {})); console.log(theGoodOne); 

Following is the basic transformation you need:

 const mystuff = [{"item1":"12", "item2":"25", "item3":"16"},{"item1":"14", "item2":"21", "item3":"18"}, {"item1":"13", "item2":"22", "item3":"17"}]; let response = []; let keys = [] for(const mystuffKeys of mystuff){ for(const k of Object.keys(mystuffKeys)) { if(!keys.includes(k)) { keys.push(k); } } } for(const key of keys) { const valArr = mystuff.map((item) => item[key]) let data = {}; data[key] = valArr; response.push(data); } console.log(response); 

I think it is better to do using es6 notation like this:

let Good = {}

mystuff.forEach(stuff=>{
  for (const key in stuff){
    Good[key] = Good[key] ? Good[key] : []
    Good[key]=[ ...Good[key], stuff[key]]
  }
})


console.log(Good)

Now the code is compact and more readable

So you want to use group by . You want to group your mystuff object by keys.

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