简体   繁体   中英

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

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

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.

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

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

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
}

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

Because the "dog" you are looking for is inside of an array, then you may also use filter function , which returns always an array of items that much the filter criteria.
If the applied filter returns an empty array then no entries for "dog".

const JSONObject = {"animals": [{name: "cat"}, {name: "dog"}]}; // Your array

const exists = JSONObject.animals.filter(item => item.name === "dog").length > 0;
console.log("Exists? " + exists); // Exists: true

You may also get a count of how many times dog exists in your array.

const JSONObject = {"animals": [{name: "cat"}, {name: "dog"}]}; // Your array

const existsCount = JSONObject.animals.filter(item => item.name === "dog").length;
console.log("Exists: " + existsCount + " time(s)"); // Exists: 1 time(s)

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

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