在lodash中嵌套父子关系,给定父ID和子项

时间:2015-08-05 12:44:57

标签: javascript jquery parent-child lodash

如果将父级及其子级作为属性提供,我将如何嵌套json对象。

数据如下:

   "1": {
        "id": 1,
        "name": "foo",
        "parent": null,
        "root": 1,
        "children": [2, 4, 6],
        "posts":[
            { "id": "1", "name": "item1" },
            { "id": "2", "name": "item2" },
            { "id": "3", "name": "item3" }
        ]
    },
    "2": {
        "id": 2,
        "name": "bar",
        "parent": 1,
        "root": 1,
        "children": null,
        "posts":[
            { "id": "4", "name": "item4" }
        ]
    },
    "3": {
        "id": 3,
        "name": "bazz",
        "parent": null,
        "root": 3,
        "children": [5, 7],
        "posts":[
            { "id": "5", "name": "item5" },
            { "id": "6", "name": "item6" }
        ]
    },
   ....

使用lodash的简单组合不会这样做。

var group = _.groupBy(data, 'parent');

这是一个小提琴:

http://jsfiddle.net/tzugzo8a/1/

问题的上下文是带有子类别的嵌套类别,类别可以包含类别和帖子。

基本上我不想为孩子和帖子拥有不同的财产,因为他们都是父母的孩子。

所需的输出

    "1": {
        "id": 1,
        "name": "foo",
        "parent": null,
        "root": 1,
        "isCategory": true,
        "children": [
             {
                 "id": 2,
                 "name": "bar",
                 "parent": 1,
                 "root": 1,
                 "isCategory": true,
                 "children": null
             },
             { "id": "1", "name": "item1", isCategory: false },
             { "id": "2", "name": "item2", isCategory: false },
             { "id": "3", "name": "item3", isCategory: false }

        ]
        ...
    }

2 个答案:

答案 0 :(得分:3)

这是我对问题的看法(fiddle):

var data = getData();

var group = getTree(data);

console.log(group);

function getTree(flat) {
    return _.reduce(flat, function (treeObj, item, prop, flatTree) {
        var children = _.map(item.children, function (childId) {
            return _.set(flatTree[childId], 'isCategory', true);
        }).concat(_.map(item.items, function(item) {
            return _.set(item, 'isCategory', false);
        }));

        item.children = !!children.length ? children : null;

        delete item.items;

        item.parent === null && (treeObj[prop] = item);

        return treeObj;
    }, {});
}

答案 1 :(得分:1)

查看更新的fiddle

var data = getData();

_.keys(data).forEach(function(id){
    var element = data[id];
    if (element.children === null){
        element.children = [];
    }

    element.isCategory = true;
    element.items.forEach(function(item){
        item.isCategory = false;
    })
});

_.keys(data).forEach(function(id){
    var element = data[id];
    element.children = element.children.map(function(childId){
      return data[childId];
    }).concat(element.items);
});

_.keys(data).forEach(function(id){
    delete data[id].items;
});

console.log(JSON.stringify(_.findWhere(_.values(data), {'parent': null})));