Vahagn
Vahagn

Reputation: 11

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?

Upvotes: 0

Views: 1524

Answers (2)

Rob Brander
Rob Brander

Reputation: 3781

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

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

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

Upvotes: 0

Related Questions