Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向Json数组添加新密钥_Javascript_Node.js_Mongodb - Fatal编程技术网

Javascript 向Json数组添加新密钥

Javascript 向Json数组添加新密钥,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,下面是Mongodb的find查询返回的json对象。我想向treatmentList数组添加一个新键。如何使用Nodejs实现这一点 我已尝试过处理列表[0]。推送({new Key1:“new Value1”}),但它不起作用 实际和预期产出如下所示- 实际产量 [ { "departmentImagepath": "", "treatmentList": [ {

下面是Mongodb的find查询返回的json对象。我想向treatmentList数组添加一个新键。如何使用Nodejs实现这一点

我已尝试过处理列表[0]。推送({new Key1:“new Value1”}),但它不起作用

实际和预期产出如下所示-

实际产量

[
    {
        "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]
也会起作用: