Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find whether a value exists in a JSON object in javascript?

I have a single level JSON to search through for the presence of a given value. Is there is a compact method provided in ecma5 for the same ?

like image 267
Rohan Avatar asked Jan 22 '26 09:01

Rohan


2 Answers

  1. Parse the JSON string with JSON.parse to get a JavaScript Object.

  2. Use in operator to check the member existence

var jsObj = JSON.parse('{"p": 5}');
console.log(jsObj);
if ("p" in jsObj) {
    console.log("`p` exists");
}
like image 91
thefourtheye Avatar answered Jan 23 '26 22:01

thefourtheye


Since it sounds like you're looking for a specific value in an unknown key, assuming there that you already parsed your JSON, you'll need something more like:

function valueExists(jsObj, value){
    for (var key in jsObj){
        if (jsObj[key] == value) return true;
    }
    return false;
}
like image 39
Dashiel N Avatar answered Jan 23 '26 23:01

Dashiel N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!