当值相同时,对象分配将覆盖先前的对象

时间:2019-05-23 11:28:31

标签: javascript ecmascript-6

因此,当在object1和object2上使用Object.assign时,我期望该对象。对象1-n范围的数目未知。

  var expectedObject = [{
         "question": {
            "value": "foo"
        },
        "question2": {
            "value": "foo1"
        },
        "question3": {
            "value": ["fooArray"]
        }
    },
{
        "question": {
            "value": "foo1"
        },
        "question2": {
            "value": "foo2"
        },
        "question3": {
            "value": ["foo1Array"]
        }
    }];

 var object1 = {
        "question": {
            "value": "foo"
        },
        "question2": {
            "value": "foo1"
        },
        "question3": {
            "value": ["fooArray"]
        }
    };

var object2 = {
        "question": {
            "value": "fooIOverrideYouSucker"
        },
        "question2": {
            "value": "fooIOverrideYouSucker1"
        },
        "question3": {
            "value": ["fooIOverrideYouSuckerWonArray"]
        }
    }
var allItems = {}; 

// This will be running inside loop - object1 and object2 are just an examples to simplify the case

Object.assign(allItems, object1, object2);

console.log(JSON.stringify([allItems]));

我得到的结果:

[{
"question": {
    "value": "fooIOverrideYouSucker"
},
"question2": {
    "value": "fooIOverrideYouSucker1"
},
"question3": {
    "value": ["fooIOverrideYouSuckerWonArray"]
}
}]

有没有一种简单的方法可以简单地将多个相同的对象附加到现有对象中?

谢谢。

以上述示例为小提琴。 https://jsfiddle.net/bielus86/fad4w2Lo/10/

1 个答案:

答案 0 :(得分:2)

如果要使用两个对象创建一个数组,则只需执行[object1, object2]

var allItems = [];
allItems.push(object1);
allItems.push(object2);