循环通过两个数组并离开连接

时间:2018-01-16 16:48:40

标签: javascript arrays loops object

我有两个数组,第一个包含工作流的各个阶段:

const workflow_stages = ["Draft", "Kick-Off", "Phase 1", "Phase 2", "Complete"];

第二个包含某些工作流阶段的任务:

const tasks = [{workflow_stage: "Kick-Off",
             tasks: ["Assignment1", "Assignment2", "Assignment3"]},
            {workflow_stage: "Phase 2",
             tasks: ["Phase2_Assignment1", "Phase2_Assigment2"]}]

如何遍历这两个数组并拥有一个组合数组,其中列出了所有workflow_stages(无论是否有任务)及其相关任务(类似于左连接):

const combined = [{workflow_stage: "Draft",
                tasks: []},
               {workflow_stage: "Kick-Off",
                tasks: ["Assignment1", "Assignment2", "Assignment3"]},
               {workflow_stage: "Phase 1",
                tasks: []},
               {workflow_stage: "Phase 2",
                tasks: ["Phase2_Assignment1", "Phase2_Assigment2"]},
               {workflow_stage: "Complete",
                tasks: []}]

2 个答案:

答案 0 :(得分:0)

您可以收集对象中的所有任务,然后将所有workflow_stage映射到具有阶段和任务的对象。

var workflow_stages = ['Draft', 'Kick-Off', 'Phase 1', 'Phase 2', 'Complete'],
    tasks = [{ workflow_stage: 'Kick-Off', tasks: ['Assignment1', 'Assignment2', 'Assignment3'] }, { workflow_stage: 'Phase 2', tasks: ['Phase2_Assignment1', 'Phase2_Assigment2'] }],
    collection = Object.create(null),
    result;

tasks.forEach(function (item) {
    collection[item.workflow_stage] = (collection[item.workflow_stage] || []).concat(item.tasks);
});

result = workflow_stages.map(function (workflow_stage) {
    return {
        workflow_stage: workflow_stage,
        task: collection[workflow_stage] || []
    };
});
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6与Map

var workflow_stages = ['Draft', 'Kick-Off', 'Phase 1', 'Phase 2', 'Complete'],
    tasks = [{ workflow_stage: 'Kick-Off', tasks: ['Assignment1', 'Assignment2', 'Assignment3'] }, { workflow_stage: 'Phase 2', tasks: ['Phase2_Assignment1', 'Phase2_Assigment2'] }],
    collection = new Map,
    result;

workflow_stages.forEach(workflow_stage => collection.set(workflow_stage, { workflow_stage, tasks: [] }));

tasks.forEach(({ workflow_stage, tasks }) => collection.get(workflow_stage).tasks.push(...tasks));

result = [...collection.values()];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以使用array#maparray#find。迭代workflow_stages数组,并检查tasks数组中对象的每个值。如果对象存在,则返回该对象,否则创建一个新对象并将其返回。

var workflow_stages = ['Draft', 'Kick-Off', 'Phase 1', 'Phase 2', 'Complete'],
    tasks = [{ workflow_stage: 'Kick-Off', tasks: ['Assignment1', 'Assignment2', 'Assignment3'] }, { workflow_stage: 'Phase 2', tasks: ['Phase2_Assignment1', 'Phase2_Assigment2'] }],
    result = workflow_stages.map(workflow_stage => {
        var task = tasks.find(o => o['workflow_stage'] === workflow_stage);
        return task ? task : {workflow_stage, tasks : []};
    });
    
console.log(result);