合并JavaScript对象

ric*_*ard 3 javascript string-concatenation

在SO上读到了另一个类似的问题,但在那个问题上没有一个明确的答案.

我得到了一些看起来像这样的JavaScript对象:

var moveJSON = {
    'name'      : move[0].innerHTML,
    'info'      : move[1].innerHTML,
    'power'     : move[2].innerHTML,
    'accuracy'  : move[3].innerHTML,
    'type'      : move[4].innerHTML,
    'category'  : move[5].innerHTML,
    'pp_min'    : move[6].innerHTML,
    'pp_max'    : move[7].innerHTML
}
Run Code Online (Sandbox Code Playgroud)

我需要将它们合并到一个对象中,它将通过AJAX发送给PHP.但首先:将它们合并为单个对象(数组)的最佳方法是什么?

Jus*_*son 5

"合并"对象与将对象放入数组(不同是聚合)不同.虽然它为您提供了一个传递的单个对象,但此聚合在结构上与合并对象不同.在访问新容器(即数组)中的值时,聚合会增加深度级别.这与合并不同,后者导致同一个容器,一个对象.

如果你正在使用Dojo,那么你可以做到:

var mergedObject = dojo.mixin(object1, object2);
Run Code Online (Sandbox Code Playgroud)

否则,这是合并两个或多个对象的简单方法:

var merge = function() {
    var result = {},
        length = arguments.length,
        object = null,
        key    = null;

    if ( length < 2 ) {
        throw "Must merge two or more objects";
    }

    for ( var i=0; i<length; ++i ) {
        object = arguments[i];
        for ( var key in object ) {
            if ( !object.hasOwnProperty(key) ) { continue; }
            result[key] = object[key];
        }
    }
    return result;
};

var mergedObject = merge({a:1}, {b:2, c:3, d: {a: 1}}, {a: 2, c:[1,2,3]});
// mergedObject looks like {a:4, b:2, c:[1,2,3], d:{a:1}}
Run Code Online (Sandbox Code Playgroud)

正如您将看到的,这与聚合非常不同:

var aggregate = function() {
    if ( length < 2 ) {
        throw "Must aggregate two or more objects";
    }

    // The following can be simplified to 
    //   return Array.prototype.slice.call(arguments);
    // but is left in a more explicit manner to illustrate the difference

    var result = [],
        length = arguments.length;

    for ( var i=0; i<length; ++i ) {
        if ( arguments.hasOwnProperty(i) ) {
            result.push(arguments[i]);
        }
    }

    return result;
};

var aggregation = aggregate({a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]});
// aggregation looks like [{a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]}];
Run Code Online (Sandbox Code Playgroud)

所以不同的是,mergedObject看起来像是{a:4, b:2, c:[1,2,3], d:{a:1}},属性d被访问mergedObject.d,而不是 aggregation,看起来像[{a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]}]d访问属性的地方aggregation[1].d.

还应该注意,由于JavaScript中提供了文字数组定义语法,因此不需要用于聚合的显式函数

var aggregation = aggregate({a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]});
Run Code Online (Sandbox Code Playgroud)

相当于

var aggregation = [{a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]}];
Run Code Online (Sandbox Code Playgroud)