首页 > 解决方案 > 在 Lodash 中按条件合并两个 JSON 数组

问题描述

我有两个 JSON 数组,如:

var a = [{_id:1, name: "Bhavin"},{_id:2, name: "Raj"},{_id:3, name: "Rahul"}];    
var b = [{_id:1, post: "Developer"},{_id:2, post: "Quality Analyst"}];

现在,我想合并喜欢:

var c = [{_id:1, name: "Bhavin", post: "Developer"},{_id:2, name: "Raj", post: "Quality Analyst"},{_id:3, name: "Rahul"}];

我知道我可以通过使用两个 for 循环在纯 JavaScript 中轻松做到这一点……但这需要n*n时间。

我想尽快解决这个问题n

我怎样才能做到这一点?

标签: javascriptecmascript-6lodash

解决方案


您应该使用lodash mergeWith功能。

var a = [{_id:1, name: "Bhavin"},{_id:2, name: "Raj"},{_id:3, name: "Rahul"}];

var b = [{_id:1, post: "Developer"},{_id:2, post: "Quality Analyst"}];


// ouput [{_id:1, name: "Bhavin", post: "Developer"},{_id:2, name: "Raj", post: "Quality Analyst"},{_id:3, name: "Rahul"}];

function customizer(firstValue, secondValue) {
  return Object.assign({}, firstValue, secondValue);
}

console.log(_.mergeWith(a, b, customizer));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>


推荐阅读