I guess you’re looking to organize the whole array so items are children of some states. Run the following snippet to get a JSON-serialized result to check it (click show code snippet to see the code and run it!):
var arr = [{
id: "1",
state: "1",
ndi: "1558.3045298",
children: "null"
}, {
id: "2",
state: "1",
ndi: "1684.0732025",
children: "null"
}, {
id: "3",
state: "1",
ndi: "1809.8418752",
children: "null"
}, {
id: "4",
state: "2",
ndi: "1915.1603572",
children: "null"
}, {
id: "5",
state: "2",
ndi: "2023.5463678",
children: "null"
}];
// This is going to hold states by id
var states = {};
// We iterate the array to get an organized by state children version
arr.forEach(function(item) {
// If state by id object hasn't the id yet we create an state object
// for current state id. There will be no duplicated states.
if (!states.hasOwnProperty(item.state)) {
states[item.state] = {
id: item.state,
children: []
};
}
// We add the item to the state by id object
states[item.state].children.push(item);
// This re-defines the state property to point to the
// item's parent state
item.state = states[item.state];
// We drop this property from the item because it's
// disturbing the new organized tree ;)
delete item.children;
});
var alreadySerialized = [];
// The second argument is required to avoid cyclic object
// serialization.
// Learn more here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
document.getElementById("result").textContent = JSON.stringify(states, function(key, val) {
if (val != null && typeof val == "object") {
if (alreadySerialized.indexOf(val) >= 0) {
return;
}
alreadySerialized.push(val);
}
return val;
});
<div id="result"></div>
Here’s a sample resulting data after the transformation:
{
"1":{
"id":"1",
"children":[
{
"id":"1",
"ndi":"1558.3045298"
},
{
"id":"2",
"ndi":"1684.0732025"
},
{
"id":"3",
"ndi":"1809.8418752"
}
]
},
"2":{
"id":"2",
"children":[
{
"id":"4",
"ndi":"1915.1603572"
},
{
"id":"5",
"ndi":"2023.5463678"
}
]
}
}
4
solved How to build a tree from a plain data structure