I am attempting to convert a deeply nested JSON object from one structure to another so that it can be properly used with the jQuery Nestable library.
Here is the original format I am working with:
{
"scanned": {
"a3": {
"value": 906
},
"value": 23667
},
"total": {
"printed": {
"black": {
"value": 44
},
"color": {
"value": 57
},
"value": 101
},
"value": 101
}
}
The desired JSON format for compatibility with the library is as follows:
[
{
"id": "scanned: 23667",
"children": [
{
"id": "a3: 906"
}
]
},
{
"id": "total: 101",
"children": [
{
"id": "printed: 101",
"children": [
{
"id": "black: 44"
},
{
"id": "color: 57"
}
]
}
]
}
]
I have attempted to traverse this tree with a recursive function but have not yet achieved the desired result:
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;
}
});
If anyone could provide me with a solution or working example, I would greatly appreciate it.