Lodash合并数组和处理重复项

时间:2017-03-07 15:43:14

标签: javascript lodash

我有两个数组:

var a = [
    {aId: 1, name: "a1"}, 
    {aId: 2, name: "a2"}
];
var b = [
    {parentId: 1, description: "b1"}, 
    {parentId: 1, description: "b2"}, 
    {parentId: 2, description: "b3"}
];

我想根据parentId === aId;

合并这些数组

我做了:

var c = _.map(a, function(obj) {
    return _.assign(obj, _.find(b, {parentId: obj.aId}));
})

JSfiddle

这可以按预期工作,但我需要它来处理重复项 - 当找到匹配项时,它会正确合并它,但我需要它将合并推送到新属性,而不是合并。

我得到了什么:

[ 
    {aId: 1, name: "a1", description: "b1"}, 
    {aId: 2, name: "a2", description: "b3"}
]

我想要的是什么:

[ 
    {
        aId: 1, 
        name: "a1", 
        b: [
            {parentId: 1, description: "b1"}, 
            {parentId: 1, description: "b2"}
        ]
     }, 
     {
        aId: 2, 
        name: "a2", 
        b: [
            {parentId: 2, description: "b1"}
        ]
     }
]

当然可以省略共同财产;

1 个答案:

答案 0 :(得分:2)

你的代码差不多完成了;在_.assign()中,您可以传递属性b等于_.filter()而不是_.find()的对象:

{
  b: _.filter(b, {parentId: obj.aId})
}

请注意_.find()返回匹配的元素,否则为undefined,_.filter()返回新的已过滤数组。

代码:



var a = [{aId: 1, name: "a1"}, {aId: 2, name: "a2"}],
    b = [{parentId: 1, description: "b1"}, {parentId: 1, description: "b2"}, {parentId: 2, description: "b3"}];

_.map(a, function(obj) {
  return _.assign(obj, {
    b: _.filter(b, {parentId: obj.aId})
  });
});

console.log(a);

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

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;