javascript - 在 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
。
我怎样才能做到这一点?
解决方案
您应该使用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>
推荐阅读
- arrays - 多维数组列表奇怪的行为
- java - 如何使用模型片段将已处理的工具项定位到右侧
- c# - 将 JSON 数据路由到 Azure 中的事件中心
- sql - Report Builder 3.0 计数参数问题
- angularjs - 如何在没有选择复选框的情况下在 Kendogrid 中选择多行 Angular5
- python-3.x - 增加图像分类器中的类数
- sqlite - 带有偏移量的sqlite3限制在android中不起作用
- html - getElementById innerHTML Runtine 错误 91
- ubuntu-16.04 - fail2ban 无法启动 ubuntu 16.04
- php - 对我的示例代码进行分页