javascript - 来自关联数组的树

标签 javascript arrays tree

有一个数组:

let docs = [      
    { "_id":"1", parent:"_", "title":"one"},
    { "_id":"2", parent:"1", "title":"two"},
    { "_id":"4", parent:"_", "title":"title"},
    { "_id":"5", parent:"4", "title":"www"},
    {"_id":"_", "name":"root" },
];

我需要离开那棵树:

{'_id':'_','name':'root','child':
    [
        {'_id':'1','parent':'_','title':'one','child':
            [
                {'_id':'2','parent':'1','title':'two','child':[]}
            ]
        },
        {'_id':'4','parent':'_','title':'title','child':
            [
                {'_id':'6','parent':'4','title':'vvv','child':[]}
            ]
        }
    ]
}

但是,只有当父元素在列表中始终高于子元素时,我的代码才有效,并且我希望使其普遍有效。

这是代码:

let node = {};
for (let doc of docs) {      
    doc.child = [];
    node[doc._id] = doc;

    if (typeof doc.parent === "undefined")
        tree = doc;
    else 
        node[doc.parent].child.push(doc);
}

console.log('tree->', JSON.stringify(tree)); 

codepen 上的代码: http://codepen.io/alex183/pen/OWvrPG?editors=0112

最佳答案

您可以使用reduce方法创建递归函数,并基本上检查当前对象的parent属性的每次迭代是否等于函数调用中传递的parent参数。

let docs = [      
    { "_id":"1", parent:"_", "title":"one"},
    { "_id":"2", parent:"1", "title":"two"},
    { "_id":"4", parent:"_", "title":"title"},
    { "_id":"5", parent:"4", "title":"www"},
    {"_id":"_", "name":"root" }
];

function makeTree(data, parent = undefined) {
  return data.reduce((r, e) => {
    // check if current e.parent is equal to parent
    if (e.parent === parent) {
      // make a copy of current e so we keep original as is
      const o = { ...e }
      // set value as output of recursive call to child prop
      o.child = makeTree(data, e._id)
      // push to accumulator
      r.push(o)
    }

    return r
  }, [])
}

console.log(makeTree(docs))

关于javascript - 来自关联数组的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42093949/

相关文章:

javascript - 向 css 添加绝对路径会导致 Gecko Engine 无法呈现页面

javascript - 在node.js中的模块之间传递mysql连接

arrays - 删除numpy数组中的列范围

arrays - swift 3 : Array to Dictionary?

r - 重复跟随父 ID 直到祖先的 Tidyverse 方法

使用B+树创建索引文件

javascript - 谷歌地图 v3 从 map 外部的链接打开信息窗口

百分比栏的 javascript 图形库

c - 非常具体的 c 数组,适合初学者

javascript - 递归函数中断