2017-03-07 136 views
3

我有兩個數組: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 ===援助合併這些陣列;

我所做的:

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"} 
     ] 
    } 
] 

共有財產當然可以省略;

+0

使用'_.filter',而不是'_.find',讓你得到所有的匹配結果到一個數組中,並相應地更新你的映射。 – Shilly

+0

謝謝,那個竅門 – Zoidy

回答

2

你的代碼快完成了;在_.assign()可以傳遞一個對象與屬性b等於的_.filter()代替_.find()結果:

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

注意_.find()返回匹配元素,否則未定義和_.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>

+0

看來_.map已經修改了原始數組,不需要c – Zoidy