合并/扩展基于每个键属性的加入JavaScript对象数组 [英] Merging/extend javascript object arrays based on join of a key property in each

查看:99
本文介绍了合并/扩展基于每个键属性的加入JavaScript对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想合并下列对象阵列,通过在id属性

I am wanting to merge the following object arrays, by first joining on the id property

var arr1 = [{
    id: 1,
    name: 'fred',
    title: 'boss'
},{
    id: 2,
    name: 'jim',
    title: 'nobody'
},{
    id: 3,
    name: 'bob',
    title: 'dancer'
}];

var arr2 = [{
    id: 1,
    wage: '300',
    rate: 'day'
},{
    id: 2,
    wage: '10',
    rate: 'hour'
},{
    id: 3,
    wage: '500',
    rate: 'week'
}];

因此​​,结果将是

So the result would be

[{
    id: 1,
    name: 'fred',
    title: 'boss',
    wage: '300',
    rate: 'day'
},{
    id: 2,
    name: 'jim',
    title: 'nobody',
    wage: '10',
    rate: 'hour'
},{
    id: 3,
    name: 'bob',
    title: 'dancer',
    wage: '500',
    rate: 'week'
}]

我想避免使用JS框架(如果可能),虽然ExtJS的已经是该项目的一部分。
目前,我有一个内部循环的循环,如果密钥匹配它复制的属性和中断内部循环,开始下一个外循环。

I would like to avoid using js frameworks (if possible), although ExtJs is already part of the project. AT the moment I have a loop with an inner loop that if the keys match it copies the properties and breaks out of the inner loop to start the next outer loop.

什么更好的建议?

推荐答案

喜欢这个?

var combined = [];
function findSecond(id,second){
    for (var i=0;i<second.length;i++){
        if(second[i].id === id){
            return second[i];
        }
    }
    return null
}

while (el = arr1.pop()){
    var getSec = findSecond(el.id,arr2);
    if (getSec){
        for (var l in getSec){
            if (!(l in el)) {
                el[l] = getSec[l];
            }
        }
        combined.push(el);
    }
}

如果阵列具有相同的长度,而id的相等,一个简单的合并将尽

If the arrays have the same length, and the id's are equal, a simpler merge will do:

function merge(a1,a2) {
    var i = -1;
    while ((i = i+1)<a1.length)  {
     for (var l in a2[i]) {
            if (!(l in a1[i] )) {
                a1[i][l] = a2[i][l];
            }
     }
    }
   return a1; 
}

下面是一个工作的例子

这篇关于合并/扩展基于每个键属性的加入JavaScript对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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