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

I have an object in JavaScript:

var obj = {
   "a": "test1",
   "b": "test2"
}

How do I check that test1 exists in the object as a value?

This question is related to javascript

The answer is


Use a for...in loop:

for (let k in obj) {
    if (obj[k] === "test1") {
        return true;
    }
}

var obj = {"a": "test1", "b": "test2"};
var getValuesOfObject = Object.values(obj)
for(index = 0; index < getValuesOfObject.length; index++){
    return Boolean(getValuesOfObject[index] === "test1")
}

The Object.values() method returned an array (assigned to getValuesOfObject) containing the given object's (obj) own enumerable property values. The array was iterated using the for loop to retrieve each value (values in the getValuesfromObject) and returns a Boolean() function to find out if the expression ("text1" is a value in the looping array) is true.


For a one-liner, I would say:

exist = Object.values(obj).includes("test1");
console.log(exist);

You can use Object.values():

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

and then use the indexOf() method:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

For example:

Object.values(obj).indexOf("test`") >= 0

A more verbose example is below:

_x000D_
_x000D_
var obj = {_x000D_
  "a": "test1",_x000D_
  "b": "test2"_x000D_
}_x000D_
_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1")); // 0_x000D_
console.log(Object.values(obj).indexOf("test2")); // 1_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1") >= 0); // true_x000D_
console.log(Object.values(obj).indexOf("test2") >= 0); // true _x000D_
_x000D_
console.log(Object.values(obj).indexOf("test10")); // -1_x000D_
console.log(Object.values(obj).indexOf("test10") >= 0); // false
_x000D_
_x000D_
_x000D_


Shortest ES6+ one liner:

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

The simple answer to this is given below.

This is working because every JavaScript type has a “constructor” property on it prototype”.

let array = []
array.constructor === Array
// => true


let data = {}
data.constructor === Object
// => true

You can use the Array method .some:

var exists = Object.keys(obj).some(function(k) {
    return obj[k] === "test1";
});

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 try this one

var obj = {
  "a": "test1",
  "b": "test2"
};

const findSpecificStr = (obj, str) => {
  return Object.values(obj).includes(str);
}

findSpecificStr(obj, 'test1');

This should be a simple check.

Example 1

var myObj = {"a": "test1"}

if(myObj.a == "test1") {
    alert("test1 exists!");
}

Try:

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

Object.keys(obj).forEach(function(key) {
  if (obj[key] == 'test1') {
    alert('exists');
  }
});
_x000D_
_x000D_
_x000D_

Or

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

var found = Object.keys(obj).filter(function(key) {
  return obj[key] === 'test1';
});

if (found.length) {
   alert('exists');
}
_x000D_
_x000D_
_x000D_

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:

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

if (Object.values(obj).includes('test1')) {
  alert('exists');
}
_x000D_
_x000D_
_x000D_


You can try this:

function checkIfExistingValue(obj, key, value) {
    return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : "jack", sex: F}, {name: "joe", sex: M}]
console.log(test.some(function(person) { return checkIfExistingValue(person, "name", "jack"); }));

I did a test with all these examples, and I ran this in Node.js v8.11.2. Take this as a guide to select your best choice.

_x000D_
_x000D_
let i, tt;
    const obj = { a: 'test1', b: 'test2', c: 'test3', d: 'test4', e: 'test5', f: 'test6' };

console.time("test1")
i = 0;
for( ; i<1000000; i=i+1) {
  if (Object.values(obj).indexOf('test4') > -1) {
    tt = true;
  }
}
console.timeEnd("test1")

console.time("test1.1")
i = 0;
for( ; i<1000000 ; i=i+1) {
  if (~Object.values(obj).indexOf('test4')) {
    tt = true;
  }
}
console.timeEnd("test1.1")

console.time("test2")
i = 0;
for( ; i<1000000; i=i+1) {
  if (Object.values(obj).includes('test4')) {
    tt = true;
  }
}
console.timeEnd("test2")


console.time("test3")
i = 0;
for( ; i<1000000 ; i=i+1) {
  for(const item in obj) {
    if(obj[item] == 'test4') {
      tt = true;
      break;
    }
  }
}
console.timeEnd("test3")

console.time("test3.1")
i = 0;
for( ; i<1000000; i=i+1) {
  for(const [item, value] in obj) {
    if(value == 'test4') {
      tt = true;
      break;
    }
  }
}
console.timeEnd("test3.1")


console.time("test4")
i = 0;
for( ; i<1000000; i=i+1) {
  tt = Object.values(obj).some((val, val2) => {
    return val == "test4"
  });
}
console.timeEnd("test4")

console.time("test5")
i = 0;
for( ; i<1000000; i=i+1) {
  const arr = Object.keys(obj);
  const len = arr.length;
  let i2 = 0;
  for( ; i2<len ; i2=i2+1) {
    if(obj[arr[i2]] == "test4") {
      tt = true;
      break;
    }
  }
}
console.timeEnd("test5")
_x000D_
_x000D_
_x000D_

Output on my server

test1:   272.325 ms
test1.1: 246.316 ms
test2:   251.98 0ms
test3:    73.284 ms
test3.1: 102.029 ms
test4:   339.299 ms
test5:    85.527 ms

if( myObj.hasOwnProperty('key') && myObj['key'] === value ){
    ...
}

getValue = function (object, key) {
    return key.split(".").reduce(function (obj, val) {
        return (typeof obj == "undefined" || obj === null || obj === "") ? obj : (_.isString(obj[val]) ? obj[val].trim() : obj[val]);}, object);
};

var obj = {
   "a": "test1",
   "b": "test2"
};

Function called:

 getValue(obj, "a");