javascript - 从对象树构造平面数组

标签 javascript arrays algorithm tree hierarchy

假设我有一棵像下面这样的对象树,可能是使用此处找到的优秀算法创建的:https://stackoverflow.com/a/22367819/3123195

{
    "children": [{
        "id": 1,
        "title": "home",
        "parent": null,
        "children": []
    }, {
        "id": 2,
        "title": "about",
        "parent": null,
        "children": [{
            "id": 3,
            "title": "team",
            "parent": 2,
            "children": []
        }, {
            "id": 4,
            "title": "company",
            "parent": 2,
            "children": []
        }]
    }]
}

(特别是在这个例子中,该函数返回的数组作为 children 数组属性嵌套在一个空对象中。)

我如何将它转换回平面数组?

最佳答案

希望您熟悉 es6:

let flatten = (children, extractChildren) => Array.prototype.concat.apply(
  children, 
  children.map(x => flatten(extractChildren(x) || [], extractChildren))
);

let extractChildren = x => x.children;

let flat = flatten(extractChildren(treeStructure), extractChildren)
               .map(x => delete x.children && x);

更新:

抱歉,没有注意到您需要设置parent 和level。请在下面找到新功能:

let flatten = (children, getChildren, level, parent) => Array.prototype.concat.apply(
  children.map(x => ({ ...x, level: level || 1, parent: parent || null })), 
  children.map(x => flatten(getChildren(x) || [], getChildren, (level || 1) + 1, x.id))
);

https://jsbin.com/socono/edit?js,console

关于javascript - 从对象树构造平面数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32609284/

相关文章:

algorithm - 有哪些算法/优化用于计算数组中元素的条件子集?

javascript - 如何使用 2 个独立的数据库,一个用于写入端,一个用于读取端。 (两个数据库通过eventbus同步)

javascript - 如何禁用网页中的 Firebug ?

php - 从 mysql 数组中回显特定值

python - 解决这个难题的最佳算法是什么?

algorithm - 包含原始详细多边形的简化(或平滑)多边形

javascript - iframe再次加载失败

javascript - 当焦点位于使用 JavaScript 的按钮时如何检测 "tab keypress"

ios - 如何在用户默认中保存对象列表?

c - 如何将每个字符一一打印出来?