How to check existence of value as hasOwnProperty JSON NodeJs

I found how to validate a key in a JSON object like this:

var myJson = {'key':'value', 'key2':'value2'};
if(myJson.hasOwnProperty('key2')){
     //do something if the key exist
}

      

Now how can I check if value2 exists? Does something like hasOwnValue exist?

+3


source to share


1 answer


As Molda suggests, there is no way to know if an object contains a specific value other than looping over the fields.

Pure JS

var myObject = {"a": 1, "b": 2};
var valueImLookingFor = 2;

for (var key in myObject) {
    if (myObject[key] === valueImLookingFor) {
        console.log('Yay, myObject contains', valueImLookingFor);
    }
}

      



There are libraries out there that do this sort of thing for you. Using Lodash's' includes () , this becomes very simple:

_.includes(myObject, valueImLookingFor); // True

      

+1


source







All Articles