Merging objects (associative arrays)

前端 未结 16 1261
野的像风
野的像风 2020-12-04 08:20

What’s the best/standard way of merging two associative arrays in JavaScript? Does everyone just do it by rolling their own for loop?

16条回答
  •  醉酒成梦
    2020-12-04 09:05

    I needed a deep-object-merging. So all of the other answers didn't help me very much. _.extend and jQuery.extend do well, unless you have a recursive array like i do. But it ain't so bad, you can program it in five minutes:

    var deep_merge = function (arr1, arr2) {
        jQuery.each(arr2, function (index, element) {
            if (typeof arr1[index] === "object" && typeof element === "object") {
                arr1[index] = deep_merge(arr1[index], element);
            } else if (typeof arr1[index] === "array" && typeof element === "array") {
                arr1[index] = arr1[index].concat(element);
            } else {
                arr1[index] = element;
            }
        });
        return arr1;
    }
    

提交回复
热议问题