2017-08-01 165 views
0

我想讓數組(從)變成像(到)。爲了在相同排列值不包括「qtty」我用:如何使用對象和嵌套數組過濾數組

_.isEqual(_.omit(val, 'qtty'), _.omit(value2, 'qtty')) 

http://underscorejs.org/#isEqual它給了正確的結果,但我沒能得到證明波紋管的最終結果。

From = 
0 {itemId: "121", qtty: 1, subitem: [], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []} 
1 {itemId: "121", qtty: 1, subitem: [], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []} 
2 {itemId: "121", qtty: 1, subitem: [{subitemId: 72, state: 1}], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []} 
3 {itemId: "141", qtty: 1, subitem: [], combo: [{comboId: 201, setId: 26}], addon: []} 
4 {itemId: "347", qtty: 1, subitem: [], combo: [], addon: []} 
5 {itemId: "347", qtty: 1, subitem: [], combo: [], addon: []} 



To = 
0 {itemId: "121", qtty: 2, subitem: [], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []} 
1 {itemId: "121", qtty: 1, subitem: [{subitemId: 72, state: 1}], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []} 
2 {itemId: "141", qtty: 1, subitem: [], combo: [{comboId: 201, setId: 26}], addon: []} 
3 {itemId: "347", qtty: 2, subitem: [], combo: [], addon: []} 

回答

0

我找到了答案here感謝響螺兔子誰張貼的答案,但它需要一個小調整,使其以更加多維數組像我的情況下工作。

function unify(orderData) { 
    var groups = _.groupBy(orderData, function (value) { 
    return value.itemId + '#' + _.map(value.subitem, function (subitemValue) { return subitemValue.subitemId + '#' + subitemValue.state ; }) + '#' + _.map(value.addon, function (addonValue) { return addonValue.addonId + '#' + addonValue.state; }) + '#' + _.map(value.combo, function (comboValue) { return comboValue.comboId + '#' + comboValue.setId; }) ; 
    }); 

    var data = _.map(groups, function (group) { 
    return { 
     itemId: group[0].itemId, 
     subitem: group[0].subitem, 
     addon: group[0].addon, 
     combo: group[0].combo, 
     qtty: _.reduce(_.pluck(group, 'qtty'), function (memo, num) { 
     return memo + num; 
     }, 0) 
    } 
    }); 
    return data; 
} 

這裏的主要區別是映射_.map()通過每個子陣列,以便能夠按一種複雜多維數組。