How to check if a value exists in an object using JavaScript

You can turn the values of an Object into an array and test that a string is present. It assumes that the Object is not nested and the string is an exact match:

var obj = { a: 'test1', b: 'test2' };
if (Object.values(obj).indexOf('test1') > -1) {
   console.log('has test1');
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values


You can use the Array method .some:

var exists = Object.keys(obj).some(function(k) {
    return obj[k] === "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');
}

Shortest ES6+ one liner:

let exists = Object.values(obj).includes("test1");