简体   繁体   中英

Loop through JSON and add new key-value data

I have a big json data set like this:

{
   "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....
}

I need to add a new "key" : "value" data in the "meta" category. I tried to use JSON.parse to convert it to JavaScript object, but it doesn't work. It says the JSON format is not correct. And even after conversion, how to actually access to meta section via a loop and add the new values there, keeping the old format and data?

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

You should use Object.keys(object) method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM