I have an object in JavaScript:
var obj = {
"a": "test1",
"b": "test2"
}
How do I check that te
You can use the Array method .some
:
var exists = Object.keys(obj).some(function(k) {
return obj[k] === "test1";
});
if( myObj.hasOwnProperty('key') && myObj['key'] === value ){
...
}
Use a for...in loop:
for (let k in obj) {
if (obj[k] === "test1") {
return true;
}
}
Shortest ES6+ one liner:
let exists = Object.values(obj).includes("test1");
Try:
var obj = {
"a": "test1",
"b": "test2"
};
Object.keys(obj).forEach(function(key) {
if (obj[key] == 'test1') {
alert('exists');
}
});
Or
var obj = {
"a": "test1",
"b": "test2"
};
var found = Object.keys(obj).filter(function(key) {
return obj[key] === 'test1';
});
if (found.length) {
alert('exists');
}
This will not work for NaN
and -0
for those values. You can use (instead of ===
) what is new in ECMAScript 6:
Object.is(obj[key], value);
With modern browsers you can also use:
var obj = {
"a": "test1",
"b": "test2"
};
if (Object.values(obj).includes('test1')) {
alert('exists');
}
For a one-liner, I would say:
exist = Object.values(obj).includes("test1");
console.log(exist);