根据属性组合两个数组

时间:2018-02-27 11:07:31

标签: javascript ecmascript-6

我有两个数组,

let student = [{ id: "weqwe", name: "john" }, { id: "wqeqweq", name: "doe" }]
let details = [
    { id: "2qweqweq", name: "larry", oName: "john" },
    { id: "231234qa", name: "jacob", oName: "john" },
    { id: "wetyrqwte", name: "jane", oName: "doe" }
]

我需要检查详细信息数组中的每个对象,并将其与student数组进行比较(与详细数组中的oName属性与student数组中的name属性进行比较),并且需要在对象属性中添加详细信息数组。还需要删除 oName ,我已经尝试过es6但是动态创建数组并且推送只给出最后一个值,请看下面的预期输出,

let output = [
    {
        id: "weqwe",
        name: "john",
        details: [
            { id: "2qweqweq", name: "larry" },
            { id: "231234qa", name: "jacob" }
        ]
    },
    {
        id: "wqeqweq",
        name: "doe",
        details: [
            { id: "wetyrqwte", name: "jane" }
        ]
    }
]

提前致谢!!

2 个答案:

答案 0 :(得分:2)

试试这个:

let student = [{ id: "weqwe", name: "john" }, { id: "wqeqweq", name: "doe" }]
let details = [
    { id: "2qweqweq", name: "larry", oName: "john" },
    { id: "231234qa", name: "jacob", oName: "john" },
    { id: "wetyrqwte", name: "jane", oName: "doe" }
];
let output = [{
        id: "weqwe",
        name: "john",
        details: [
            { id: "2qweqweq", name: "larry" },
            { id: "231234qa", name: "jacob" }
        ]
    },
    {
        id: "wqeqweq",
        name: "doe",
        details: [
            { id: "wetyrqwte", name: "jane" }
        ]
    }
];
let result = student.map((obj) => {
    obj.details = details.filter(o => o.oName === obj.name).map(({oName,...other}) =>other);
    return obj;
});

console.log(result);

答案 1 :(得分:1)

let student = [{id:"weqwe", name:"john"}, {id:"wqeqweq", name:"doe"}]
let details = [
              {id:"2qweqweq", name:"larry", oName:"john"},
              {id:"231234qa", name:"jacob", oName:"john"},
              {id:"wetyrqwte", name:"jane", oName:"doe"}
              ]


let output= student.map(student=> {

  const detailsObj = details.filter(({oName})=>  oName === student.name)
  return {...student, details: detailsObj.map(({oName, ...other})=> other)}
})

console.log(output)