将新密钥添加到Json数组

时间:2017-11-03 17:24:53

标签: javascript node.js mongodb

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

我已经尝试过treatmentList [0] .push({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
            }
        ]
    }
]

2 个答案:

答案 0 :(得分:1)

假设您获得的json对象被保存到名为obj

的变量中
var list = obj[0].treatmentList;
list[0]['new Key1'] = 'new value1'; 

答案 1 :(得分:0)

您可以使用array#forEach遍历数组并使用括号表示法为对象添加新的键值。

const arr = [{"departmentImagepath": "","treatmentList": [{"shortDescription": "my shortdescription","healingTimeInDays": "8",},{"shortDescription": "my new shortdescription","healingTimeInDays": "10",}]}];
arr.forEach(o => o.treatmentList.forEach((ob,i) => ob['new Key'+ (i + 1)] = 'new value' + (i + 1)));
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }