javascript – Loop through JSON Object

Question:

I have this json:

var json =    {
     "0":{
       "check":true,
       "OBJECT_ID":{
         "check":false,
         "name":"OBJECT_ID",
         },
      "nameTable":"TEST1",
      "EVENT_NAME_MANAGE":{
         "check":false,
         "name":"EVENT_NAME_MANAGE",
      }}
     "1":{
      "check":true,
      "OBJECT_ID":{
         "check":false,
         "name":"OBJECT_ID",
      },
      "nameTable":"TEST1",
      "EVENT_NAME_MANAGE":{
         "check":false,
         "name":"EVENT_NAME_MANAGE",
      }
     }
    }

I would like that if I get 0 or 1, change the value of ObJECT_ID and EVENT_NAME to true

I have tried doing this for:

    for (var i in json) {
        console.log(json[i].nameTable)
    }

As they pass me 0 or 1, I have to go through what is inside them (in my example I only have 2 the ObJECT_ID and EVENT_NAME but I have many more) and change the check value that is inside them to true

Answer:

Check the following program. In it, the existence of the check property of each element is check to assign it true if so.

let json = {
      "0":{
       "check":true,
       "OBJECT_ID":{
         "check":false,
         "name":"OBJECT_ID",
         },
      "nameTable":"TEST1",
      "EVENT_NAME_MANAGE":{
         "check":false,
         "name":"EVENT_NAME_MANAGE",
      }},
     "1":{
      "check":true,
      "OBJECT_ID":{
         "check":false,
         "name":"OBJECT_ID",
      },
      "nameTable":"TEST1",
      "EVENT_NAME_MANAGE":{
         "check":false,
         "name":"EVENT_NAME_MANAGE",
      }
     }
    };
 
for (let i in json) {
  for (let j in json[i]) {
    if (json[i][j].hasOwnProperty('check')) {
      json[i][j].check = true;
    }
  }
}

console.log("Mostrando resultado final:");
console.log(json);

Based on the edit you provide me, it is more efficient to do the following:

let json = {
      "0":{
       "check":true,
       "OBJECT_ID":{
         "check":false,
         "name":"OBJECT_ID",
         },
      "nameTable":"TEST1",
      "EVENT_NAME_MANAGE":{
         "check":false,
         "name":"EVENT_NAME_MANAGE",
      }},
     "1":{
      "check":true,
      "OBJECT_ID":{
         "check":false,
         "name":"OBJECT_ID",
      },
      "nameTable":"TEST1",
      "EVENT_NAME_MANAGE":{
         "check":false,
         "name":"EVENT_NAME_MANAGE",
      }
     }
    };
 
/* Sólo debemos cambiar los elementos 0 y 1 si existen */
$scope.toggle = function(isCheck, index) {
 if (json.hasOwnProperty(index)) {
  /* No es necesario usar index.toString() */
   for (let j in json[index]) {
    if (json[index][j].hasOwnProperty('check')) {
      json[index][j].check = isCheck;
    }
   }
 }
}

console.log("Mostrando resultado final:");
console.log(json);

If you receive, as you say in your question, 50 or more records it is a waste of time to go through each and every one of the elements if you only search for two in particular, the index 0 and 1 .

Scroll to Top