javascript - Search for an element and it parents in object -
i have object
$scope.categories = [ { value: 'one', id: 1, childs: [ { value: 'two', id : 2, childs: [ { value: 'three', id: 3 }, { value: 'four', id: 4 } ] }, { value: 'five', id: 5 }, { value: 'six', id: 6, childs: [ { value: 'seven', id: 7 }, { value: 'eight', id: 8 } ] } ] }, { value: 'nine', id: 9 } ];
how can element , parents if know id? use angularjs, doesn't me solve task think...
use function flat array:
function flat(o, parent) { let res = [] o.foreach(child => { child.parent = parent res.push(child) if (child.childs) { array.prototype.push.apply(res, flat(child.childs, child.id)) } }) return res }
usage:
let categories = [ { value: 'one', id: 1, childs: [ { value: 'two', id : 2, childs: [ /* ... */ ] }, /* ... */ ] ]; let flat_categories = flat(categories)
results:
array[9]: [ { value: 'one', id: 1, childs: [/*...*/], parent: undefined }, { value: 'two', id: 2, childs: [/*...*/], parent: 1 }, ... ]
you can easy find id , parent
Comments
Post a Comment