Javascript 向Json数组添加新密钥
下面是Mongodb的find查询返回的json对象。我想向treatmentList数组添加一个新键。如何使用Nodejs实现这一点 我已尝试过处理列表[0]。推送({new Key1:“new Value1”}),但它不起作用 实际和预期产出如下所示- 实际产量Javascript 向Json数组添加新密钥,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,下面是Mongodb的find查询返回的json对象。我想向treatmentList数组添加一个新键。如何使用Nodejs实现这一点 我已尝试过处理列表[0]。推送({new Key1:“new Value1”}),但它不起作用 实际和预期产出如下所示- 实际产量 [ { "departmentImagepath": "", "treatmentList": [ {
[
{
"departmentImagepath": "",
"treatmentList": [
{
"shortDescription": "my shortdescription",
"healingTimeInDays": "8",
},
{
"shortDescription": "my new shortdescription",
"healingTimeInDays": "10",
}
]
}
]
预期产量
[
{
"departmentImagepath": "",
"treatmentList": [
{
"shortDescription": "my shortdescription",
"healingTimeInDays": "8",
"new Key1": "new value1" //New key to be added
},
{
"shortDescription": "my new shortdescription",
"healingTimeInDays": "10",
"new Key2": "new value2" //New key to be added
}
]
}
]
假设您得到的json对象被保存到一个名为
obj
var list = obj[0].treatmentList;
list[0]['new Key1'] = 'new value1';
您可以使用array#forEach
遍历数组,并使用括号表示法向对象添加新的键值
const arr=[{“departmentImagepath”:“,”治疗列表“:[{“shortDescription”:“我的shortDescription”,“healingTimeInDays”:“8”,},{“shortDescription”:“我的新shortDescription”,“healingTimeInDays”:“10”,}];
arr.forEach(o=>o.treatmentList.forEach((ob,i)=>ob['newkey'+(i+1)]='newvalue'+(i+1));
控制台日志(arr)代码>
。作为控制台包装{max height:100%!important;top:0;}
arr[0][“treatmentList”][0][“new Key1”]=“new Value1”
不知何故它不起作用…@derek[mcve]
也会起作用: