Rohan
Rohan

Reputation: 3332

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 ?

Upvotes: 2

Views: 11529

Answers (4)

mehdi
mehdi

Reputation: 354

The shortest solution:

    var jsObj = JSON.parse('{"v": 10}');
    if (jsObj.v==10) {
        console.log("`v=`"+jsObj.v);
    }

  

Upvotes: 0

Dashiel N
Dashiel N

Reputation: 319

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

Upvotes: 2

Deepak Ingole
Deepak Ingole

Reputation: 15742

Parse the JSON string with JSON.parse to get a JavaScript Object, and do

Simplest check,

if(jsonObj['key']) {
}

Working fiddle

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239493

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

    Output

    { p: 5 }
    `p` exists
    

Upvotes: 10

Related Questions