2017-02-14 40 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