var obj = [{
id: 1,
child:[2,4],
data : \"hello\"
},{
id: 2,
child:[3],
data : \"I m second\"
},
{
id: 3,
child:[],
data : \"I
A proposal with a temporary object for keeping the reference to the items.
var array = [{ id: 1, child: [2, 4], data: "hello" }, { id: 2, child: [3], data: "I m second" }, { id: 3, child: [], data: "I m third" }, { id: 4, child: [6], data: "I m fourth" }, { id: 5, child: [], data: "I m fifth" }, { id: 6, child: [], data: "I m sixth" }],
tree = [];
array.forEach(function (a) {
if (!this[a.id]) {
this[a.id] = { id: a.id };
tree.push(this[a.id]);
}
this[a.id].data = a.data;
this[a.id].child = a.child.map(function (b) {
this[b] = this[b] || { id: b };
return this[b];
}, this);
}, Object.create(null));
document.write('' + JSON.stringify(tree, 0, 4) + '
');