Reputation: 11
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 !
Upvotes: 0
Views: 87
Reputation: 440
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
Upvotes: 0
Reputation: 11
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);
Upvotes: 0
Reputation: 26844
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);
Upvotes: 1
Reputation: 40566
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);
Upvotes: 3