Javascript基于公共元素合并数组 [英] Javascript merge arrays based on common element

查看:70
本文介绍了Javascript基于公共元素合并数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个从两个独立对象获取信息的对象(取自ajax调用)。基本上我们有一个标签列表,还有一个元素列表,这些项是相关的,但是标签对象不包含我填充所有数据所需的所有信息。
例如:

I'm trying to create a single object which takes information from two separate objects (taken from ajax calls). Basically we have a list of tags, and also a list of elements, these items are related, however the tag object doesn't contain all of the information I need to populate all the data. For example:

标签列表:

[
    {"id": 1, "name": "yadda", "description": "yadda yadda"},
    {"id": 2, "name": "yadda1", "description": "yadda yadda1"},
    {"id": 7, "name": "yadda2", "description": "yadda yadda2"},
    {"id": 10, "name": "yadda3", "description": "yadda yadda3"}
]

元素列表(更多信息):

List of Elements (more info):

[
    {"id": 1, "icon": "icon1.gif"},
    {"id": 2, "icon": "icon2.gif"},
    {"id": 7, "icon": "icon3.gif"},
    {"id": 10, "icon": "icon4.gif"}
]

我需要通过ID比较两个对象,并将它们组合成一个新对象,使我能够访问这两个对象中的所有数据。

I need to compare the two objects by the ID, and combine them into a new object that gives me access to all of the data in both of those objects.

如果它有帮助,这是一个有角度的项目,我已经在使用下划线,我相信必须有一些方法用下划线做这个,但我不是很熟悉它。

If it helps, this is an angular project, and I am already using Underscore, I believe there must be some way to do this with underscore, but i'm not very familliar with it.

推荐答案

又快又脏:

var a = [
        {"id": 1, "name": "yadda", "description": "yadda yadda"},
        {"id": 2, "name": "yadda1", "description": "yadda yadda1"},
        {"id": 7, "name": "yadda2", "description": "yadda yadda2"},
        {"id": 10, "name": "yadda3", "description": "yadda yadda3"}
    ], 
    b = [
        {"id": 1, "icon": "icon1.gif"},
        {"id": 2, "icon": "icon2.gif"},
        {"id": 7, "icon": "icon3.gif"},
        {"id": 10, "icon": "icon4.gif"}
    ];

var result = a.map(function(v){

    var ret;

    $.each(b, function(k, v2){

        if(v2.id === v.id){
            ret = $.extend({}, v2, v); // merge the objects in to a new one
            return false; // break the loop
        }      

    });

    return ret;

});

console.log(result);

http://jsfiddle.net/YwUA2/

如您所见,这假设两者中的对象之间存在1:1的关系数组。

As you can see, this assumes that there's a 1:1 relationship between the objects in the two arrays.

这篇关于Javascript基于公共元素合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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