JavaScript的合并通过ID对象 [英] JavaScript merging objects by id

查看:141
本文介绍了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.

我试图用 _。工会来做到这一点,但它只是覆盖从第二个数组中的值入第1

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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆