我有两个JSON对象,我想将newData
附加到existingData。
existingData = {"School Name" : "Albert"}
newData = {"Teacher Name" : "Ms. Mithcell"}
这是我想要的输出:
existingData = {"School Name" : "Albert" , "Teacher Name" : "Ms. Mithcell"};
我该怎么做?
答案 0 :(得分:1)
JavaScript具有Object.assign
功能。
请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
existingData = {"School Name" : "Albert"}
newData = {"Teacher Name" : "Ms. Mithcell"}
Object.assign(existingData, newData)
console.log(existingData); // {School Name: "Albert", Teacher Name: "Ms. Mithcell"}
Object.assign(originalObject,newObject)将返回合并了newObject的originalObject。
答案 1 :(得分:1)
对于JavaScript其object
而不是像dictionary
:P这样的python,只需使用Spread语法即可完成工作。
existingData = {"School Name" : "Albert"}
newData = {"Teacher Name" : "Ms. Mithcell"}
result = {...existingData, ...newData};
console.log(result);
答案 2 :(得分:1)
您可以通过这种方式来采用更传统的方法:
existingData = {"School Name" : "Albert"};
newData = {"Teacher Name" : "Ms. Mithcell"};
var new_keys = Object.keys(newData);
for (var i = 0; i < new_keys.length; i++){
existingData[new_keys] = newData[new_keys[i]];
}
console.log(existingData);