"myfield": {
"answers": {
"Key1": "value1",
"Key2": "value2"
}
}
var Obj2={"key3":"value3"}
我正在努力使用javascript将Obj2放入 myfield 对象
预期结果:
"myfield": {
"answers": {
"Key1": "value1",
"Key2": "value2",
"Key3": "value3"
}
}
答案 0 :(得分:5)
您可以使用Object.assign()
来获得所需的结果。
var obj1 = {
"myfield": {
"answers": {
"Key1": "value1",
"Key2": "value2"
}
}
}
var obj2 = {
"key3": "value3"
}
Object.assign(obj1.myfield.answers, obj2);
console.log(obj1)

答案 1 :(得分:0)
使用for in
var data = {
"myfield": {
"answers": {
"Key1": "value1",
"Key2": "value2"
}
}
}
var obj2 = {
"key3": "value3"
}
for(k in obj2){
data["myfield"]["answers"][k] = obj2[k]
}
console.log(data);
答案 2 :(得分:0)
var json='{'+
'"answers": {'+
'"Key1": "value1",'+
'"Key2": "value2"'+
' }'+
'}';
console.log(JSON.parse(json));
var obj=JSON.parse(json);
obj.answers.key3="value3";
console.log('"myfield":'+JSON.stringify(obj));