Convert Json Object Containing Objects Into An Array Of Objects
My data is currently stored in this format, stored in a JSON file: { 'name': { '0': ______, '1': ______, '2': ______ }, 'xcoord': { '0':
Solution 1:
This can be done for instance with two imbricated .forEach()
:
var obj = {
"name": {
0: 'name0',
1: 'name1',
2: 'name2'
},
"xcoord": {
0: 'xcoord0',
1: 'xcoord1',
2: 'xcoord2'
},
"ycoord": {
0: 'ycoord0',
1: 'ycoord1',
2: 'ycoord2'
}
};
var res = [];
Object.keys(obj).forEach(k => {
Object.keys(obj[k]).forEach(v => {
(res[v] = (res[v] || { id: v }))[k] = obj[k][v];
});
});
console.log(res);
Note:
This line ...
(res[v] = (res[v] || { id: v }))[k] = obj[k][v]
... is a short way to do:
if(!res[v]) {
// if this record doesn't exist yet,// create it with its implied 'id' property
res[v] = { id: v };
}
// add property 'k' to this record
res[v][k] = obj[k][v];
Post a Comment for "Convert Json Object Containing Objects Into An Array Of Objects"