我想附加到这个对象:
var obj =
{
"myKey":
{
"subkey": [1,2,3]
}
};
这是我要附加到obj
var addKeys = {
"subkey2" [3,4,5],
"subkey3" [5,6,7]
}
我想做obj.myKey.push(addKeys);
之类的事情,但我知道这只适用于数组。我的最终目标应该最终看起来像这样:
var obj =
{
"myKey":
{
"subkey": [1,2,3],
"subkey2" [3,4,5],
"subkey3" [5,6,7]
}
};
答案 0 :(得分:5)
var obj =
{
"myKey":
{
"subkey": [1,2,3]
}
};
var addKeys = {
"subkey2": [3,4,5],
"subkey3": [5,6,7]
};
Object.assign(obj.myKey, addKeys)
console.log(obj);
Object.assign将覆盖第一个参数。它被称为“破坏性”操作。如果要合并对象并返回一个新对象:
var obj =
{
"myKey":
{
"subkey": [1,2,3]
}
};
var addKeys = {
"subkey2": [3,4,5],
"subkey3": [5,6,7]
};
var merged = Object.assign({}, obj.myKey, addKeys)
console.log(merged);
console.log(obj);
答案 1 :(得分:3)