简体   繁体   English

合并JavaScript对象

[英]Merge JavaScript objects

I've read another similiar question on SO but there wasn't a clear answer at that question. 我已经阅读了关于SO的另一个类似问题,但该问题没有明确答案。

I got some JavaScript objects that look like this: 我得到了一些看起来像这样的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
}

I need to merge them into one object, that will be send to PHP via AJAX. 我需要将它们合并为一个对象,该对象将通过AJAX发送到PHP。 But first: what's the best way to merge them into a single object (array)? 但首先:将它们合并为单个对象(数组)的最佳方法是什么?

"Merging" objects is different than putting objects into an array, which is an aggregation. “合并”对象与将对象放入数组(聚合)不同。 Although it provides you with a single object to pass around, this aggregate is structurally different than a merged object. 尽管它为您提供了一个可以传递的对象,但此聚合在结构上与合并的对象不同。 Aggregating adds a level of depth when accessing values in the new container, which is an array. 访问新容器(数组)中的值时,聚合会增加深度级别。 This is different from merging which results in the same container, an object. 这与合并会导致相同的容器即对象不同。

If you're using Dojo, than you can just do: 如果您使用的是Dojo,则可以执行以下操作:

var mergedObject = dojo.mixin(object1, object2);

Otherwise, here's a simple way of merging two or more objects: 否则,这是合并两个或更多对象的简单方法:

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}}

As you'll see, this is very different than an aggregation: 如您所见,这与聚合非常不同:

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]}];

So the difference is that mergedObject looks like {a:4, b:2, c:[1,2,3], d:{a:1}} , where property d is accessed as mergedObject.d , as opposed to aggregation , which looks like [{a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]}] and where property d is accessed as aggregation[1].d . 因此不同之处在于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访问。

It should also be noted that an explicit function for aggregation isn't necessary thanks to the literal array definition syntax available in JavaScript 还应注意,由于JavaScript中提供了文字数组定义语法,因此不需要显式的聚合函数

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

is equivalent to 相当于

var aggregation = [{a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]}];

This should work. 这应该工作。

var array = []

array.push(yourObject);

this will put your object into an array, which should be used if you were putting of a collection of the same object into one. 这会将您的对象放入一个数组,如果您将同一对象的集合放入一个数组,则应使用该数组。

to merge different values into one object: 将不同的值合并到一个对象中:

function makeObject(){
        var obj = {};

 obj['info']  = somevalue;    //arguments [0] maybe
 obj['power']  = somevalue;    
 obj['accuracy']   = somevalue;
 obj['type']       = somevalue;
 obj['category']   = somevalue;
 obj['pp_min']     = somevalue;
 obj['pp_max']    = somevalue;

return obj;

} }

Here is a link also describing passing arguments like array into a function in JavaScript which could be useful in creating the merged object. 这是一个链接,还描述了将数组之类的参数传递到JavaScript中的函数中,这可能对创建合并对象很有用。

http://www.cherny.com/webdev/60/javascript-function-arguments-default-values-passing-objects-and-overloading http://www.cherny.com/webdev/60/javascript-function-arguments-default-values-passing-objects-and-overloading

If you have multiple JSON objects, you can create a containing JSON object: 如果您有多个JSON对象,则可以创建一个包含JSON对象:

var containerJSON = {};

And use that object as an array: 并将该对象用作数组:

containerJSON[0] = moveJSON_1;
containerJSON[1] = moveJSON_2;

Then in PHP you can use json_decode() to get your data back. 然后在PHP中,您可以使用json_decode()取回数据。

This is a simple mixin function that will not overwrite existing object properties 这是一个简单的mixin函数,不会覆盖现有的对象属性

var mixin = function(addToJSON, someOtherJSON) {
  for(var key in someOtherJSON) {
     // don't overwrite 
     if(!moveJSON[key]) {
       moveJSON[key] = someOtherJSON[key]; 
     }
  }
};

var otherJSON = {'someOtherStuff': someOtherMoves[0].innerHTML};

mixin(moveJSON, otherJSON);

That should do what you need. 那应该做您需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM