简体   繁体   English

检查 JSON 对象中是否存在值

[英]Check whether a value exists in JSON object

I have the next JSON:我有下一个 JSON:

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

What is the best way to know if the "dog" value exists in the JSON object?了解 JSON 对象中是否存在“狗”值的最佳方法是什么?

Thanks.谢谢。

Solution 1解决方案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)解决方案 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)解决方案 3(使用 some() 方法)

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". JSON 变量指的是具有一个名为“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下面的函数可用于检查 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然后检查 JSON 是否包含该值

_isContains(JSONObject, "dog")

See this fiddle: https://jsfiddle.net/ponmudi/uykaacLw/看到这个小提琴: 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.但无需关心密钥,只需检查 JSON 是否包含给定值即可。 So that the function can be used to find any value irrespective of the key.因此该函数可用于查找任何值,而不管键如何。

Why not JSON.stringify and .includes() ?为什么不是JSON.stringify.includes()

You can easily check if a JSON object includes a value by turning it into a string and checking the string.您可以通过将 JSON 对象转换为字符串并检查该字符串来轻松检查 JSON 对象是否包含值。

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

Edit: make sure to check browser compatibility for .includes()编辑:确保检查.includes()浏览器兼容性

You could improve on the answer from Ponmudi VN:您可以改进Ponmudi VN 的答案:

  • Shorter Code较短的代码
  • Look for a key and a value查找

See this fiddle: https://jsfiddle.net/solarbaypilot/sn3wtea2/看到这个小提琴: 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.此示例将您的 JSON 放入正确的格式并进行存在检查。 I use jquery for convenience.为方便起见,我使用 jquery。

http://jsfiddle.net/nXFxC/ 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.因为您要查找的“狗”在一个数组内,所以您也可以使用filter function ,它始终返回一个与过滤条件相同的项目数组。
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.您还可以计算 dog 在您的阵列中存在的次数。

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:我有下一个JSON:

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

What is the best way to know if the "dog" value exists in the JSON object?知道JSON对象中是否存在“ dog”值的最佳方法是什么?

Thanks.谢谢。

Solution 1解决方案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)解决方案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)解决方案3(使用some()方法)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM