sum
我有一个像上面这样的树结构的对象数组,我希望像这样获得所有独特的路径
abstract-sequence
这是我的对象
root1
child1
child2
grandchild1
grandchild2
child3
root2
child1
child2
grandchild1
greatgrandchild1
我到达树中的所有节点
Food->Dry Food Items->Local Dry Food Items
Food->Dry Food Items->Thai Dry Food Items
Food->Dry Food Items->Others
Food->Fruits
------
------
答案 0 :(得分:1)
您可以使用递归并使用forEach
循环创建函数。
var arr = [{"id":1,"name":"Food","parent_id":0,"children":[{"id":5,"name":"Dry Food Items","parent_id":1,"children":[{"id":11,"name":"Local Dry Food Items","parent_id":5},{"id":12,"name":"Thai Dry Food Items","parent_id":5},{"id":60,"name":"Others","parent_id":5}]},{"id":6,"name":"Fruits","parent_id":1},{"id":7,"name":"LG Branded","parent_id":1},{"id":8,"name":"Meat","parent_id":1},{"id":9,"name":"Sea food","parent_id":1},{"id":10,"name":"Vegetables","parent_id":1,"children":[{"id":14,"name":"Local Vegetables","parent_id":10},{"id":15,"name":"Thai Vegetables","parent_id":10}]},{"id":38,"name":"Frozen","parent_id":1},{"id":39,"name":"IP Kitchen","parent_id":1,"children":[{"id":40,"name":"IP Meat","parent_id":39},{"id":41,"name":"IP Starter","parent_id":39},{"id":42,"name":"IP Ingredients","parent_id":39},{"id":43,"name":"IP Sauce","parent_id":39},{"id":44,"name":"IP Seafood","parent_id":39},{"id":45,"name":"IP Starter","parent_id":39},{"id":46,"name":"IP Desert","parent_id":39}]}]},{"id":2,"name":"Beverage","parent_id":0,"children":[{"id":16,"name":"Bar","parent_id":2},{"id":17,"name":"Coffee & Tea","parent_id":2},{"id":18,"name":"In Can","parent_id":2},{"id":19,"name":"Water","parent_id":2},{"id":47,"name":"IP Bar","parent_id":2}]},{"id":3,"name":"Disposable","parent_id":0,"children":[{"id":21,"name":"Disposable","parent_id":3}]},{"id":4,"name":"SOE","parent_id":0,"children":[{"id":20,"name":"Cleaning Materials","parent_id":4},{"id":22,"name":"Chinaware","parent_id":4}]}]
function getNames(data) {
var result = [];
function loop(data, c) {
data.forEach(function (e) {
var name = !c.length ? e.name : c + '->' + e.name;
if (e.children) { loop(e.children, name); }
else {
result.push({ name: name });
}
});
}
loop(data, '');
return result;
}
console.log(getNames(arr))