0

have an array of objects in the following structure

    [
        {id: 1, title: 'hello', parent: 0},
        {id: 2, title: 'hello', parent: 0},
        {id: 3, title: 'hello', parent: 1},
        {id: 4, title: 'hello', parent: 3},
        {id: 5, title: 'hello', parent: 4},
        {id: 6, title: 'hello', parent: 4},
        {id: 7, title: 'hello', parent: 3},
        { id: 8, title: 'hello', parent: 2}
    ]

I would like to make a new array with the following structure

    [
          {id: 1, title: 'hello', parent: 0, children: [
          {id: 3, title: 'hello', parent: 1, children: [
          {id: 4, title: 'hello', parent: 3, children: [
          {id: 5, title: 'hello', parent: 4},
          {id: 6, title: 'hello', parent: 4}
          ]},
          {id: 7, title: 'hello', parent: 3}
          ]}
          ]},
          {id: 2, title: 'hello', parent: 0, children: [
          {id: 8, title: 'hello', parent: 2}
          ]}
    ]
cloudworks
  • 599
  • 1
  • 3
  • 18
  • Since you are basically talking about how to build and utilize a tree structure, let me point to a possibly relevant question. http://stackoverflow.com/questions/8640823/what-javascript-tree-data-structures-are-available Not marking as duplicate as the original question does not make clear whether that data format desired is a hard requirement. – Mike Brant Jul 29 '15 at 17:11

1 Answers1

0

Try this:

// Original array
var array = [        
    {id: 1, title: 'hello', parent: 0},
    {id: 2, title: 'hello', parent: 0},
    {id: 3, title: 'hello', parent: 1},
    {id: 4, title: 'hello', parent: 3},
    {id: 5, title: 'hello', parent: 4},
    {id: 6, title: 'hello', parent: 4},
    {id: 7, title: 'hello', parent: 3},
    { id: 8, title: 'hello', parent: 2}
];

// Nesting
var obj, ii, o;
for(var i = 0; i < array.length; i++) {
    obj = array[i];
    if(obj.parent > 0) {
        for(var ii = 0; ii < array.length; ii++) {
            o = array[ii];
            if(o.id == obj.parent) {
                if(!o.children) o.children = [];
                o.children.push(obj);
                break;
            }
        }
    }
}


// Cleanup
var tempArray = [];
var obj;
for(var i = 0; i < array.length; i++) {
    obj = array[i];
    if(obj.parent == 0) {
        tempArray.push(obj);
    }
}
array = tempArray;

// Log to check how everything turned out
console.log(array);

http://jsfiddle.net/sxb5fzak/2/

nilsree
  • 302
  • 1
  • 7