合并3数组并在lodash中加入字段?

时间:2018-10-28 07:58:18

标签: javascript lodash

请帮助我,我想合并3个数组以与字段 _id 合并。我的数组就是这样。我尝试通过 _id 合并所有数组,但是仍然无法正常工作,我也不知道。

//array 1
let  inventory =[ 
 { _id: '0001',
   itemId: '0001',
   onHandQty:  70,
   avgCost: 9,
   balanceAmount: 630,
 },
 { _id: '0002',
   itemId: '0002',
   onHandQty: 70,
   avgCost: 5,
   balanceAmount: 350,
 }
]
//array 2
let  po =[
 {
   _id : "0002",    
   onHandPO : 10
 },
 {
   _id : "0001",    
   onHandPO : 20
 }
]

//array 3
let  so =[
 {     
  _id: "0001",  
  onHandSO: 2
 },
 {
  _id: "0003",  
  onHandSO: 1
 }
]

我希望所有通过_id连接的数组成为一个这样的数组。我需要这个结果。

let  inventory =[ 
 { _id: '0001',
   itemId: '0001',
   onHandQty:  70,
   avgCost: 9,
   balanceAmount: 630,
   onHandPO : 20,
   onHandSO: 2
 },
 { _id: '0002',
   itemId: '0002',
   onHandQty: 70,
   avgCost: 5,
   balanceAmount: 350,
   onHandPO : 10
 },
 { _id: '0003',
   itemId: '0002',
   onHandQty: 0,
   avgCost: 0,
   balanceAmount: 0,
   onHandPO : 0
   onHandSO: 1
 }
]

1 个答案:

答案 0 :(得分:1)

您可以展平所有数组,将它们按公用值分组,然后将所有值分配给单个对象。然后得到结果。

var inventory = [{ _id: '0001', itemId: '0001', onHandQty: 70, avgCost: 9, balanceAmount: 630 }, { _id: '0002', itemId: '0002', onHandQty: 70, avgCost: 5, balanceAmount: 350 }],
    po = [{ _id: "0002", onHandPO: 10 }, { _id: "0001", onHandPO: 20 }],
    so = [{ _id: "0001", onHandSO: 2 }, { _id: "0003", onHandSO: 1 }],
    result = _([inventory, po, so])
        .flatten()
        .groupBy('_id')
        .map(values => _.assign({}, ...values))
        .value();

console.log(_.sumBy(result, 'onHandSO')); // total of onHandSO 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>