简体   繁体   中英

How to check JSON element exist

This is the JSON I get

entityData = [
   {
      "is_place":false,
      "type":[
         "Person"
      ],
      "is_organization":false,
      "name":[
         "Kevin Presto"
      ],
      "occurrences":38,
      "is_person":true,
      "jobTitle":[
         "Vice President"
      ],
      "label":"Presto"
   },
   {
      "is_place":false,
      "label":[
         "Paris salon",
         "Paris Salonu",
         "Salon (mostra)"
      ],
      "occurrences":1,
      "is_person":false
   },
   {
      "is_place":false,
      "label":"IEP Paris",
      "is_organization":true,
      "occurrences":1,
      "is_person":false
   }
]

But it comes as a text format,

   if (entityData === Array) {
      console.log('entityData is Array!');
   } else {
      console.log('Not an array');
   }

Then I loop through to find if is_place is true

for (_i = 0, _len = entityData.length; _i < _len; _i++) {
  entity = entityData[_i];
  console.log('for loop going '+entity)
  if (entity.is_place === true) {
    console.log('place found found')
  }
}

But above code log each and every character of the entityData Where I'm wrong.

UPDATE : I was following @shreedhar answer and got following error, any idea where I'm doing wrong.

TypeError: entityData.forEach is not a function
entityData.forEach(function(entity,i){

Since is_place property is false in all objects of array, code within if block within for loop will not be executed.

for (var _i = 0, _len = entityData.length; _i < _len; _i++) { var entity = entityData[_i]; console.log('for loop going '+ entity) if (entity.is_place === true) { console.log('place found') } else { console.log('place not found'); } }

always prefer array.forEach to iterate an array.

entityData.forEach(function(entity){ console.log('entity is', entity); if(entity[i].is_place){ console.log('Place found', entity[i]); } else { console.log('Place not found'); } });

try this

 entityData = '[{"is_place":false,"type":["Person"],"is_organization":false,"name":["Kevin Presto"],"occurrences":38,"is_person":true,"jobTitle":["Vice President" ],"label":"Presto"},{"is_place":false,"label":["Paris salon","Paris Salonu","Salon (mostra)"],"occurrences":1,"is_person":false},{"is_place":false,"label":"IEP Paris","is_organization":true,"occurrences":1,"is_person":false}]'; entityData = JSON.parse(entityData); for (_i = 0, _len = entityData.length; _i < _len; _i++) { entity = entityData[_i]; console.log('for loop going ', entity) if (entity.is_place === true) { console.log('place found found') } } 

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