【问题标题】:Adding new key to Json array向 Json 数组添加新键
【发布时间】:2017-11-03 17:24:52
【问题描述】:

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

我尝试过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
            }
        ]
    }
]

【问题讨论】:

  • arr[0]["treatmentList"][0]["new Key1"] = "new Value1"
  • 不知何故无法正常工作...
  • @derek [mcve] 也会这样做:minimal reproducible example

标签: javascript node.js mongodb


【解决方案1】:

假设你得到的 json 对象被保存到一个名为obj的变量中

var list = obj[0].treatmentList;
list[0]['new Key1'] = 'new value1'; 

【讨论】:

    【解决方案2】:

    您可以使用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; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 2013-09-23
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多