[javascript] Check whether a value exists in JSON object

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

This question is related to javascript json

The answer is


I think this is the best and easy way:

$lista = @()

$lista += ('{"name": "Diego" }' | ConvertFrom-Json)
$lista += ('{"name": "Monica" }' | ConvertFrom-Json)
$lista += ('{"name": "Celia" }' | ConvertFrom-Json)
$lista += ('{"name": "Quin" }' | ConvertFrom-Json)

if ("Diego" -in $lista.name) {
    Write-Host "is in the list"
    return $true

}
else {
    Write-Host "not in the list"
    return $false
}

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

 var Duplicate= JSONObject .find(s => s.name== "cat");
        if (typeof (Duplicate) === "undefined") {
           alert("Not Exist");
           return;
        } else {
            if (JSON.stringify(Duplicate).length > 0) {
                alert("Value Exist");
                return;
            }
        }

Why not JSON.stringify and .includes()?

You can easily check if a JSON object includes a value by turning it into a string and checking the string.

console.log(JSON.stringify(JSONObject).includes("dog"))
--> true

Edit: make sure to check browser compatibility for .includes()


Below function can be used to check for a value in any level in a JSON

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

then to check if JSON contains the value

_isContains(JSONObject, "dog")

See this fiddle: https://jsfiddle.net/ponmudi/uykaacLw/

Most of the answers mentioned here compares by 'name' key. But no need to care about the key, can just checks if JSON contains the given value. So that the function can be used to find any value irrespective of the key.


iterate through the array and check its name value.


You could improve on the answer from Ponmudi VN:

  • Shorter Code
  • Look for a key and a value

See this fiddle: https://jsfiddle.net/solarbaypilot/sn3wtea2/

function _isContains(json, keyname, value) {

return Object.keys(json).some(key => {
        return typeof json[key] === 'object' ? 
        _isContains(json[key], keyname, value) : key === keyname && json[key] === value;
    });
}

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


document.getElementById('dog').innerHTML = _isContains(JSONObject, "name", "dog");
document.getElementById('puppy').innerHTML = _isContains(JSONObject, "name", "puppy");

This example puts your JSON into proper format and does an existence check. I use jquery for convenience.

http://jsfiddle.net/nXFxC/

<!-- HTML -->
<span id="test">Hello</span><br>
<span id="test2">Hello</span>

//Javascript

$(document).ready(function(){
    var JSON = {"animals":[{"name":"cat"}, {"name":"dog"}]};

if(JSON.animals[1].name){      
$("#test").html("It exists");
}
if(!JSON.animals[2]){       
$("#test2").html("It doesn't exist");
}
});

Check for a value single level

const hasValue = Object.values(json).includes("bar");

Check for a value multi-level

function hasValueDeep(json, findValue) {
    const values = Object.values(json);
    let hasValue = values.includes(findValue);
    values.forEach(function(value) {
        if (typeof value === "object") {
            hasValue = hasValue || hasValueDeep(value, findValue);
        }
    })
    return hasValue;
}