I'm trying to change a deep nested JSON object from one structure to another. In order to be able to use it in the correct format to work with the library called jQuery Nestable.
This is the origin format I have:
{
"scanned": {
"a3": {
"value": 906
},
"value": 23667
},
"total": {
"printed": {
"black": {
"value": 44
},
"color": {
"value": 57
},
"value": 101
},
"value": 101
}
}
The desired JSON format to work with the library is this:
[{
"id": "scanned: 23667",
"children": [{
"id": "a3: 906"
}]
}, {
"id": "total: 101",
"children": [{
"id": "printed: 101",
"children": [{
"id": "black: 44"
}, {
"id": "color: 57"
}]
}]
}]
I tried to traverse that tree with recursive function but so far didn't reach the desired outcome:
Object.keys(o).forEach(function (k) {
if (o[k] !== null && typeof o[k] === 'object') {
if(parent) {
console.log(parent);
if(!o.children) {
o.children = [];
}
o.children.push({id: k + ": " + o[k].value})
} else {
o.id = k + ": " + o[k].value
}
_this.iter(o[k], k);
return;
}
});
Can anyone please provide me with a working example?
Try following
let obj = {"total":{"printed":{"black":{"value":44},"color":{"value":57},"value":101},"value":101}};
/* Rest parameters where other other keys are collected in rest object */
function processObj({value, ...rest}, r=[]) {
/* Iterate over each key/value pair in rest object */
Object.entries(rest).forEach(([k,v], i) => {
if(Array.isArray(r)) { // For first level items
r[i] = {"id" : `${k}: ${v.value}`};
processObj(v, r[i]);
} else { // For child nodes
r.children = r.children || [];
r.children[i] = {"id" : `${k}: ${v.value}`};
processObj(v, r.children[i]);
}
});
return r;
}
console.log(processObj(obj))