2017-02-14 59 views
0

我有一個大的JSON數據集是這樣的:遍歷JSON並添加新鍵值數據

{ 
    "10001": { 
     "coords": [ 
      "40.753793,-74.007026/40.750272,-74.00828", 
      "40.751445,-74.00143/40.752055,-74.000975", 
      "40.751439,-73.99768/40.752723,-73.99679" 
     ], 
     "meta": { 
      "city": "New York", 
      "state": "NY", 
      "latCenter": 40.71, 
      "lngCenter": -73.99 
     } 
    }, 
    "10002": { 
     "coords": [ 
      "40.714069,-73.997504/40.709181,-73.996222/40.709485,-73.994022" 
     ], 
     "meta": { 
      "city": "New York", 
      "state": "NY", 
      "latCenter": 40.71, 
      "lngCenter": -73.99 
     } 
    }, 
    and so on.... 
} 

我需要在"meta"類別中添加一個新的"key" : "value"數據。我試圖使用JSON.parse將其轉換爲JavaScript對象,但它不起作用。它說JSON格式不正確。甚至在轉換之後,如何通過循環實際訪問元節,並在那裏添加新值,保持舊格式和數據?

+0

請發表您的當前代碼 – Zinc

+0

基本上你需要一些關鍵的,比如'10001'。並用它作爲對象的訪問器。 –

+1

*「它表示JSON格式不正確。」*它實際上**說了什麼?除了「等等......」部分,上面顯示的內容是有效的JSON。 –

回答

1

const data = { 
 
    "10001": { 
 
     "coords": [ 
 
      "40.753793,-74.007026/40.750272,-74.00828", 
 
      "40.751445,-74.00143/40.752055,-74.000975", 
 
      "40.751439,-73.99768/40.752723,-73.99679" 
 
     ], 
 
     "meta": { 
 
      "city": "New York", 
 
      "state": "NY", 
 
      "latCenter": 40.71, 
 
      "lngCenter": -73.99 
 
     } 
 
    }, 
 
    "10002": { 
 
     "coords": [ 
 
      "40.714069,-73.997504/40.709181,-73.996222/40.709485,-73.994022" 
 
     ], 
 
     "meta": { 
 
      "city": "New York", 
 
      "state": "NY", 
 
      "latCenter": 40.71, 
 
      "lngCenter": -73.99 
 
     } 
 
    } 
 
}; 
 

 
// inject key "hello" with value "world" 
 
Object.keys(data).forEach(key => Object.assign(data[key].meta, { "hello": "world" })); 
 

 
console.log(data);

+0

非常感謝! – Vahagn

0

您應該使用Object.keys(object)方法:

var obj={ 
 
    "10001": { 
 
     "coords": [ 
 
      "40.753793,-74.007026/40.750272,-74.00828", 
 
      "40.751445,-74.00143/40.752055,-74.000975", 
 
      "40.751439,-73.99768/40.752723,-73.99679" 
 
     ], 
 
     "meta": { 
 
      "city": "New York", 
 
      "state": "NY", 
 
      "latCenter": 40.71, 
 
      "lngCenter": -73.99 
 
     } 
 
    }, 
 
    "10002": { 
 
     "coords": [ 
 
      "40.714069,-73.997504/40.709181,-73.996222/40.709485,-73.994022" 
 
     ], 
 
     "meta": { 
 
      "city": "New York", 
 
      "state": "NY", 
 
      "latCenter": 40.71, 
 
      "lngCenter": -73.99 
 
     } 
 
    } 
 
} 
 

 
var keys=Object.keys(obj); 
 
for(i=0;i<keys.length;i++){ 
 
    obj[keys[i]]["meta"]["key"]=0; 
 
} 
 
console.log(obj);

+0

感謝您的幫助! – Vahagn