循环遍历json树对象并创建新数组

时间:2018-06-13 13:27:23

标签: javascript loops ecmascript-6

有没有一种方法可以让JS / ES6循环通过一个对象,它是子节点并创建新的对象树数组。

我有这个json树对象:

[
{
    id: "001",
    deparmentsIds: [
        "002",
        "003"
    ],
    details: {
        parentDeparmentsId: null,
        name: "Top"
    }
},
{
    id: "002",
    deparmentsIds:[
        "004"
    ],
    details: {
        parentDeparmentsId: ["001"],
        name: "Operations"
    }
},
{
    id: "003",
    deparmentsIds:[]
    details: {
        parentDeparmentsId: ["001"],
        name: "Support"
    }
},
{
    id: "004",
    deparmentsIds:[]
    details: {
        parentDeparmentsId: ["002"],
        name: "Support operations"
    }
}

我想创建一个如下所示的新对象数组树: enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用单个循环收集对象中的所有信息,并仅返回没有父级的节点。



function getTree(data, root) {
    var o = {};
    data.forEach(({ id, details: { parentDeparmentsId: parent, name } }) => {
        var temp = { id, name };
        if (o[id] && o[id].children) {
            temp.children = o[id].children;
        }
        o[id] = temp;
        o[parent] = o[parent] || {};
        o[parent].children = o[parent].children || [];
        o[parent].children.push(temp);
    });
    return o[root].children;
}

var data = [{ id: "001", deparmentsIds: ["002", "003"], details: { parentDeparmentsId: null, name: "Top" } }, { id: "002", deparmentsIds: ["004"], details: { parentDeparmentsId: ["001"], name: "Operations" } }, { id: "003", deparmentsIds: [], details: { parentDeparmentsId: ["001"], name: "Support" } }, { id: "004", deparmentsIds: [], details: { parentDeparmentsId: ["002"], name: "Support operations" } }],
    tree = getTree(data, null);

console.log(tree);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

您可以使用reducemap方法创建递归函数来创建嵌套对象结构。



const data = [{"id":"001","deparmentsIds":["002","003"],"details":{"parentDeparmentsId":null,"name":"Top"}},{"id":"002","deparmentsIds":["004"],"details":{"parentDeparmentsId":"001","name":"Operations"}},{"id":"003","deparmentsIds":[],"details":{"parentDeparmentsId":"001","name":"Support"}},{"id":"004","deparmentsIds":[],"details":{"parentDeparmentsId":"002","name":"Support operations"}}]

function tree(input, parentId) {
  return input.reduce((r, e) => {
    if (e.id == parentId || parentId == undefined && e.details.parentDeparmentsId == null) {
      const children = [].concat(...e.deparmentsIds.map(id => tree(input, id)))
      const obj = {
        [e.details.name]: children
      }
      r.push(obj)
    }
    return r;
  }, [])
}

const result = tree(data)
console.log(result)