2017-11-03 15 views
-2

以下はMongodbのfindクエリで返されたjsonオブジェクトです。私はtreatList配列に新しいキーを追加したいと思います。Nodejsを使ってどのように達成できますか?Json配列に新しいキーを追加する

私が試みたtreatmentList [0] .push({新しいキー1: "新しい値1"})が、その動作していない

実際と期待される出力が以下に与えられる -

実際の出力

[ 
    { 
     "departmentImagepath": "",   
     "treatmentList": [ 
      {         
       "shortDescription": "my shortdescription", 
       "healingTimeInDays": "8",     
      }, 
      { 
       "shortDescription": "my new shortdescription", 
       "healingTimeInDays": "10",  
      } 
     ] 
    } 
] 

の予想される出力

あなたが得るJSONオブジェクトがに保存されていると仮定すると、
[ 
    { 
     "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 
      } 
     ] 
    } 
] 
+0

http://idownvotedbecau.se/nomcve/ –

+0

'のARR [0] [ "treatmentList"] [0] [ "新しいキー1"] = "新しい値1"' – kgangadhar

+0

何とかそれが動作していない... –

答えて

0

と呼ばれます。

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; }

1

変数は、あなたがあなたの配列を反復処理し、あなたのオブジェクトに新しいキーと値を追加するには、ブラケット表記を使用するarray#forEachを使用することができますobj

var list = obj[0].treatmentList; 
list[0]['new Key1'] = 'new value1'; 
関連する問題