I have a JSON that looks like this:
var json = [{
"name": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f",
"parent": "null"
}, {
"name": "0xe8f84d8ad5850d66bd289ce3199753c35f4cbf40",
"parent": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f"
}, {
"name": "0x8fa01b60f503a3873c1b02ef351112f57cdd818e",
"parent": "0xe8f84d8ad5850d66bd289ce3199753c35f4cbf40"
}, {
"name": "0x753a018eca49f1b1e8b46b88d6a7b449478740e0",
"parent": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f"
}]
I am attempting to rewrite it using Javascript into a new JSON structure with the following order:
var json = [{
"name": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f",
"parent": "null",
"children": [{
"name": "0x753a018eca49f1b1e8b46b88d6a7b449478740e0",
"parent": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f"
}, {
"name": "0xe8f84d8ad5850d66bd289ce3199753c35f4cbf40",
"parent": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f",
"children": [{
"name": "0x8fa01b60f503a3873c1b02ef351112f57cdd818e",
"parent": "0xe8f84d8ad5850d66bd289ce3199753c35f4cbf40"
}]
}]
}]
In this new structure, children are created and nested under their parent object. Each name is unique, the first object has no parent ("null"), and some objects may not have any children ("null" or an empty array []).
I'm not very familiar with Javascript and I'm unsure of how to achieve this. I've tried different loops without success, such as:
json.forEach(function(link) {
var parent = link.parent = nodeByName(json,link.parent),
child = link.children = nodeByName(json,link.children);
if (parent.children) parent.children.push(child);
else parent.children = [child];
});
This results in:
[{
"name": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f",
"parent": {
"name": "null",
"children": [{}]
},
"children": {}
}, {
"name": "0xe8f84d8ad5850d66bd289ce3199753c35f4cbf40",
"parent": {
"name": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f",
"children": [{}, {}]
},
"children": {}
}, {
"name": "0x8fa01b60f503a3873c1b02ef351112f57cdd818e",
"parent": {
"name": "0xe8f84d8ad5850d66bd289ce3199753c35f4cbf40",
"children": [{}]
},
"children": {}
}, {
"name": "0x753a018eca49f1b1e8b46b88d6a7b449478740e0",
"parent": {
"name": "0xcd963fe5b4d9de5380130d6c6b6cfb5d3b903b1f",
"children": [{}, {}]
},
"children": {}
}]