如何合并Javascript中的对象数组? [英] How do I merge an array of objects in Javascript?

查看:45
本文介绍了如何合并Javascript中的对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

var array1 = [ {'key':1, 'property1': 'x'}, {'key':2, 'property1': 'y'} ]
var array2 = [ {'key':2, 'property2': 'a'}, {'key':1, 'property2': 'b'} ]

我想要merge(array1,array2)给我:

I want merge(array1, array2) to give me:

[
    {'key':1, 'property1': 'x', 'property2' : 'b'},
    {'key':2, 'property1': 'y', 'property2' : 'a'}
]

有一种简单的方法吗?

几个人回答的时候并没有仔细研究我的问题,请注意,我想匹配每个数组中的相似对象并将它们的属性组合到我的最终数组中.键是唯一的,每个数组中最多只能有一个带有特定键的对象.

several people have answered without looking too closely at my problem, please be note that I want to match similar objects in each array and combine their properties into my final array. Keys are unique and there will only ever be at most one object with a particular key in each array.

推荐答案

我写了一个 quick 不太快的解决方案.您可能要考虑的一个问题是,第二个数组中对象的属性是否应该覆盖与之比较的第二个对象中的相同属性(如果存在).

I wrote a quick not-so-quick solution. The one problem you might want to consider is whether a property from an object in the second array should override the same property, if present, in the second object it's being compared to.

此解决方案的复杂度为 O(n²).解决方案2更快.此解决方案仅适用于不想快速刺猬Sanic 的用户.

This solution is of complexity O(n²). Solution 2 is much faster; this solution is only for those who don't want to be Sanic the Hedgehog fast.

JavaScript

var mergeByKey = function (arr1, arr2, key) {
// key is the key that the function merges based on
    arr1.forEach(function (d, i) {
        var prop = d[key];
        // since keys are unique, compare based on this key's value
        arr2.forEach(function (f) {
            if (prop == f[key]) {    // if true, the objects share keys
                for (var x in f) {   // loop through each key in the 2nd object
                    if (!(x in d))   // if the key is not in the 1st object
                        arr1[i][x] = f[x];    // add it to the first object
                // this is the part you might want to change for matching properties
                // which object overrides the other?
                }
            }
        })
    })
    return arr1;
}

测试用例

var arr = [ {'key':1, 'property1': 'x'},
            {'key':2, 'property1': 'y'} ],
    arr2= [ {'key':2, 'property2': 'a'},
            {'key':1, 'property2': 'b'} ];

console.log(mergeByKey(arr, arr2, "key"));

结果

/* returns:
    Object
    key: 1
    property1: "x"
    property2: "b"
    __proto__: Object
and 
    Object
    key: 2
    property1: "y"
    property2: "a"
    __proto__: Object
*/

小提琴

解决方案2

正如 Vivin Paliath 在以下评论中指出的那样,我的第一个解决方案是 O(n²)复杂度(阅读:不好).他的回答非常好,并提供了一个复杂度为 O(m + n)的解决方案,其中 m 是第一个数组的大小, n .换句话说,复杂度为 O(2n).

fiddle

Solution 2

As Vivin Paliath pointed out in the comments below, my first solution was of O(n²) complexity (read: bad). His answer is very good and provides a solution with a complexity of O(m + n), where m is the size of the first array and n of the second array. In other words, of complexity O(2n).

但是,他的解决方案没有解决对象内部的对象.为了解决这个问题,我使用了递归-阅读:魔鬼,就像 O(n²).

However, his solution does not address objects within objects. To solve this, I used recursion—read: the devil, just like O(n²).

JavaScript

var mergeByKey = function (arr1, arr2, key) {
    var holder = [],
        storedKeys = {},
        i = 0; j = 0; l1 = arr1.length, l2 = arr2.length;

    var merge = function (obj, ref) {
        for (var x in obj) {
            if (!(x in ref || x instanceof Object)) {
                ref[x] = obj[x];
            } else {
                merge(obj[x], ref[x]);
            }
        }
        storedKeys[obj.key] = ref;
    }
    for (; i < l1; i++) {
        merge(arr1[i], storedKeys[arr1[i].key] || {});
    }
    for (; j < l2; j++) {
        merge(arr2[j], storedKeys[arr2[j].key] || {});
    }

    delete storedKeys[undefined];

    for (var obj in storedKeys)
        holder.push(storedKeys[obj]);

    return holder;
}

测试用例

var arr1 = [
    {
        "key" : 1,
        "prop1" : "x",
        "test" : {
            "one": 1,
            "test2": {
                "maybe" : false,
                "test3": { "nothing" : true }
            }
        }
    },
    {
        "key" : 2,
        "prop1": "y",
        "test" : { "one": 1 }
    }],
    arr2 = [
        {
            "key" : 1,
            "prop2" : "y",
            "test" : { "two" : 2 }
        },
        {
            "key" : 2,
            "prop2" : "z",
            "test" : { "two": 2 }
        }];
console.log(mergeByKey(arr1, arr2, "key"));

结果

/*
Object
    key: 1
    prop1: "x"
    prop2: "y"
    test: Object
        one: 1
        test2: Object
            maybe: false
            test3: Object
                nothing: true
                __proto__: Object
            __proto__: Object
        two: 2
        __proto__: Object
    __proto__: Object
Object
    key: 2
    prop1: "y"
    prop2: "z"
    test: Object
        one: 1
        two: 2
        __proto__: Object
    __proto__: Object
*/

这将正确合并对象以及所有子对象.该解决方案假定具有匹配的 key 的对象具有相同的层次结构.它也不能处理两个数组的合并.

This correctly merges the objects, along with all child objects. This solutions assumes that objects with matching keys have the same hierarchies. It also does not handle the merging of two arrays.

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

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