I have an array structured like the following:
var persons= [{name: 'John',
id: 1,
children :[{name :'John Jr',
id: 11,
children :[{name: 'John Jr Jr'
id: 111}]
},
{name :'Jane'
id: 12}]
},
{name:'Peter',
id :2
},
...]
It is basically an array of objects, the objects are persons, each person may have any number of descendants which are by them selves arrays of person objects. The number of descendants of each person is unknown.
What I am trying to achieve is to have a map structured this way:
var personsMap =[1 : 'John',
11: 'John > John Jr',
111 : 'John > John Jr > John Jr Jr',
12: 'John > Jane',
...
]
It is a map of each possible combination of each path, so by querying the map by the person's id, it should return the string of it's parent > grand-parent >...
I'am trying to build this map recursively so what I have tried so far:
var personsMap = {};
function buildParentsMap (persons){
$.each (persons, function(ndx, person){
if(person.children && person.children.length > 0){
buildParentsMap(person.children);
}
personsMap[person.id] = person.name;
});
console.log(personsMap);
}
But this outputs the following :
[1 : 'John',
11: 'John Jr',
111 'John Jr Jr',
12: 'Jane',
...]
It is all the names but without being concatenated the way I explained above. How can I achieve this? Thanks