Jon Lamb Jon Lamb - 1 month ago 9
Javascript Question

Add Sequential Number To Javascript Objects In Nested Object Tree

I have an object like the one below and am looking for a way to add one property to each sub object in the tree. That is, I want to add a number to the object that counts up from 0 to n. I know I can traverse through the object with a recursive function but because of variable scope I'm not able to use a simple incremented variable to count up as I go through the tree.

Current Object:

var tree = [
{
name: 'a',
children: []
},{
name: 'b',
children: [
{
name: 'c',
children: []
}
]
},
{
name: 'd',
children: [
{
name: 'e',
children: [
{
name: 'f',
children: []
},
{
name: 'g',
children: []
}
]
}
]
}
];


Desired Object:

var tree = [
{
name: 'a',
number: 0,
children: []
},{
name: 'b',
number: 1,
children: [
{
name: 'c',
number: 2,
children: []
}
]
},
{
name: 'd',
number: 3,
children: [
{
name: 'e',
number: 4,
children: [
{
name: 'f',
number: 5,
children: []
},
{
name: 'g',
number: 6,
children: []
}
]
}
]
}
];

Answer

You just need to set counter variable outside of recursive function and increment it before you loop object.

var tree = [{"name":"a","children":[]},{"name":"b","children":[{"name":"c","children":[]}]},{"name":"d","children":[{"name":"e","children":[{"name":"f","children":[]},{"name":"g","children":[]}]}]}];

function addNumber(input) {
  var counter = 0;

  function rec(data) {
    data.forEach(function(e) {
      if (typeof e == 'object' && !Array.isArray(e)) {
        e.number = counter++;
        for (var p in e) {
          if (typeof e[p] == 'object') rec(e[p])
        }
      } 
    })
  }
  rec(input)
}

addNumber(tree);
console.log(tree)

Comments