JavaScript merging objects by id(JavaScript 按 id 合并对象)
问题描述
在 Javascript 中合并两个数组的正确方法是什么?
What's the correct way to merge two arrays in Javascript?
我有两个数组(例如):
I've got two arrays (for example):
var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]
我希望能够得到类似的结果:
I want to be able to end up with something like:
var a3 = [{ id : 1, name : "test", count : "1"},
{ id : 2, name : "test2", count : "2"}]
根据id"字段连接两个数组,并简单地添加额外数据.
Where the two arrays are being joined based on the 'id' field and extra data is simply being added.
我尝试使用 _.union
来执行此操作,但它只是将第二个数组中的值覆盖到第一个数组中
I tried to use _.union
to do this, but it simply overwrites the values from the second array into the first one
推荐答案
这应该可以解决问题:
var mergedList = _.map(a1, function(item){
return _.extend(item, _.findWhere(a2, { id: item.id }));
});
这里假设a1中第二个对象的id应该是2而不是2"
This assumes that the id of the second object in a1 should be 2 rather than "2"
这篇关于JavaScript 按 id 合并对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 按 id 合并对象


- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01