使用lodash将子列表提升为父级

时间:2016-06-22 17:04:02

标签: lodash

我现在试图绕着lodash包围我,并想弄清楚如何用它来处理这种特殊情况,而不是写一个foreach循环。

该对象具有活动和任务的结构。 ActivityList有许多活动。每个活动都有简单的属性和一系列任务。每个任务数组都具有简单的属性。我想生成一个表,列出所有活动中包含一些活动属性的所有任务。

例如:

{
"Activities": [{
    "Name": "Activity1",
    "Tasks": [{
        "Name": "Task1",
        "Complete": "90%"
    }, {
        "Name": "Task2",
        "Complete": "40%"
    }, {
        "Name": "Task3",
        "Complete": "97%"
    }]
}, {
    "Name": "Activity2",
    "Tasks": [{
        "Name": "Task4",
        "Complete": "100%"
    }, {
        "Name": "Task5",
        "Complete": "25%"
    }, {
        "Name": "Task6",
        "Complete": "17%"
    }]
}]
}

我希望这可以作为

    Activity1 Task1 90%
    Activity1 Task2 40%
    Activity1 Task3 97%
    Activity2 Task4 100%

我认为我已经开始单独使用基本命令,但在将它们链接在一起时,我错过了一些东西。我认为这需要地图,flattendeep和pluck的一些组合,但我还没有能够弄明白。任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

var data = { ... }; // your object with the activities array

var result = _.flatMap(data.Activities, function (activity) { 
    return _.map(activity.Tasks, function (task) { 
        return { activity: activity.Name, task: task.Name, complete: task.Complete };
    });
});

然后结果将解析为一个对象数组:

 [
    {"activity":"Activity1","task":"Task1","complete":"90%"},
    {"activity":"Activity1","task":"Task2","complete":"40%"},
    {"activity":"Activity1","task":"Task3","complete":"97%"},
    {"activity":"Activity2","task":"Task4","complete":"100%"},
    {"activity":"Activity2","task":"Task5","complete":"25%"},
    {"activity":"Activity2","task":"Task6","complete":"17%"}
]

您可以循环浏览项目以创建表格。