Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a value exists in JSON object

Tags:

I have the next JSON:

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]}; 

What is the best way to know if the "dog" value exists in the JSON object?

Thanks.

Solution 1

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]}; ... for (i=0; i < JSONObject.animals.length; i++) {     if (JSONObject.animals[i].name == "dog")         return true; } return false; 

Solution 2 (JQuery)

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]}; ... $.map(JSONObject.animals, function(elem, index) {  if (elem.name == "dog")       return true; }); return false; 

Solution 3 (using some() method)

function _isContains(json, value) {     let contains = false;     Object.keys(json).some(key => {         contains = typeof json[key] === 'object' ?          _isContains(json[key], value) : json[key] === value;         return contains;     });     return contains; } 
like image 795
Ivan Avatar asked Jun 17 '11 10:06

Ivan


People also ask

How do you check if a key exists in JSON object and get its value?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().

How do you check key is exist or not in JSON?

jquery json provide several method for getting key value or check if key exists etc. In this example we will use hasOwnProperty method of json object that will help to check if key exists or not in jquery. hasOwnProperty return true if key is exists and return false if key is not exists on given javascript json.


1 Answers

var JSON = [{"name":"cat"}, {"name":"dog"}]; 

The JSON variable refers to an array of object with one property called "name". I don't know of the best way but this is what I do?

var hasMatch =false;  for (var index = 0; index < JSON.length; ++index) {   var animal = JSON[index];   if(animal.Name == "dog"){    hasMatch = true;    break;  } } 
like image 188
Vijay Sirigiri Avatar answered Sep 30 '22 16:09

Vijay Sirigiri