下划线如何组合两个对象数组?

时间:2017-08-01 14:07:13

标签: underscore.js

我有两个数组,oldBalances和newBalances

var oldBalances =  [
  {name: 'vacation', value: '21'},
  {name: 'account', value: '200'},
]

var newBalances = [
  {name: 'vacation', value: '25'},
  {name: 'order', value: '15'}
]

var allBalances = []

我希望allBalances数组合并所有余额,但如果旧版本中的余额名称与新版本相同,我想采用新版本

var allBalances = [
  {name: 'account', value: '200'},
  {name: 'vacation', value: '25'},
  {name: 'order', value: '15'}
]

1 个答案:

答案 0 :(得分:0)

我会用这种方式解决这个问题:

let allBalances = [];

_([...newBalances, ...oldBalances]).each(balanceItem => {
    if (_(allBalances).where({name: balanceItem.name).length) {
        // skip adding key that is added already
        continue;
    }
    allBalances.push(balanceItem);
});