212

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?

0

23 Answers 23

187

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

Sign up to request clarification or add additional context in comments.

5 Comments

This is part of Ecma2017, it's not yet available for most uses :(
Not supported in IE 11 and Edge, it's better to use for..in loop as described below
Slightly less verbose: if(Object.values(obj).includes('test1')) { ... }
Tbh, I like @nickb version far better maybe consider an update?
This doesn't work for me if the value includes number like "fieldAb2c".
109

Shortest ES6+ one liner:

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

2 Comments

Mind though that IE does not support .includes(), so use it only server side with Node or if you simply don't care about IE.
Who uses IE anyway. It needs removing.
65

You can use the Array method .some:

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

2 Comments

Less verbose, with Object.values: ``` var exists = Object.values(obj).some(function(k) { return k === "test1"; }); ```
Object.values not support IE. I recommend to use Object.keys developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
52

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

Comments

36

Use a for...in loop:

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

2 Comments

@Gregor it doesn't matter as 'k' is defined again when it takes the next value.
highly underrated answer, the performance on this one s better than any other method
22

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:

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


console.log(Object.values(obj).indexOf("test1")); // 0
console.log(Object.values(obj).indexOf("test2")); // 1

console.log(Object.values(obj).indexOf("test1") >= 0); // true
console.log(Object.values(obj).indexOf("test2") >= 0); // true 

console.log(Object.values(obj).indexOf("test10")); // -1
console.log(Object.values(obj).indexOf("test10") >= 0); // false

Comments

16

For a one-liner, I would say:

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

Comments

14

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.

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

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

Comments

5

you can try this one

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

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

findSpecificStr(obj, 'test1');

Comments

4

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

Comments

2

In new version if ecma script now we can check vslues by ?. operations..

Its so simpler and easy yo check values in a object or nested or objects

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

if(obj?.a) return "i got the value"

Similarly since in Javascript most used primitive type is Object

We can use this arrays, functions etc too

aFunc = () => { return "gotcha"; }

aFunc?.() // returns gotcha

myArray = [1,2,3]

myArray?.[3] // returns undefined

Thanks

1 Comment

This does not answer the user's question. He is asking how to check for "values" and your method checks for "keys".
2

ES2017 introduces a new method called Object.values() that allows you to return an array of own enumerable property’s values of an object.

You can do this to check if the value exists in the Object Values:

let found = Object.values(africanCountries).includes('Nigeria');
if (found) {
     // code
}

You can also check if it exists in the Object Keys:

let found = Object.keys(africanCountries).includes('Nigeria');
if (found) {
     // code
}

Comments

1

Best way to find value exists in an Object using Object.keys()

obj = {
 "India" : {
 "Karnataka" : ["Bangalore", "Mysore"],
 "Maharashtra" : ["Mumbai", "Pune"]
 },
 "USA" : {
 "Texas" : ["Dallas", "Houston"],
 "IL" : ["Chicago", "Aurora", "Pune"]
 }
}

function nameCity(e){
    var finalAns = []
    var ans = [];
    ans = Object.keys(e).forEach((a)=>{
        for(var c in e[a]){
            e[a][c].forEach(v=>{
                if(v === "Pune"){
                    finalAns.push(c)
                }
            })

        }
    })
    console.log(finalAns)
}


nameCity(obj)

Comments

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

2 Comments

Did you use other libraries when implementing this solution?
No @SherwinAblañaDapito Ablaña Dapito
0
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.

Comments

0

For complex structures, here is how I do it:

const obj = {
    test: [{t: 't'}, {t1: 't1'}, {t2: 't2'}],
  rest: [{r: 'r'}, {r1: 'r1'}, {r2: 'r2'}]
}

console.log(JSON.stringify(obj).includes(JSON.stringify({r1: 'r1'}))) // returns true
console.log(JSON.stringify(obj).includes(JSON.stringify({r1: 'r2'}))) // returns false

Comments

0

Please refer docs: https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Object/values

Object.values returns an array and thus any array operation be it array.includes, array.some, indexOF will let you check if the value exists or not.

Comments

0

To check is value exists in each object key in javascript and want to return the object.

let arr = [{
    firstname: "test1",
    middlename: "test2",
    surname: "test3",
    age:20
},
{
    firstname: "test4",
    middlename: "test5",
    surname: "test6",
    age:25
},
{
    firstname: "test7",
    middlename: "test2",
    surname: "test8",
    age:30
}];

let filteredObjects = arr.filter((item) => Object.keys(item).some(key => item[key] === "test2"));

This will return objects by comparing each key pair in each object.

Answer:

[{
    firstname: "test1",
    middlename: "test2",
    surname: "test3",
    age:20
},
{
    firstname: "test7",
    middlename: "test2",
    surname: "test8",
    age:30
}]

Hope this is helpful!

Comments

0

I like the solutions, I also added an extended solution for nested objects:

const Person = {
    name: 'Omar', lastname: 'Ruiz', age: 24,
    nested: { attribute: false }
}

function checkValuesRecursively(o, value) {
    if (typeof o === 'object') {
        for (const prop in o) {
            const isValuePresent = checkValuesRecursively(o[prop], value);
            if (isValuePresent) return true;
        }
    } else if (o === value) {
        return true;
    }
    return false;
}

const result = checkValuesRecursively(Person, 24);
console.log(result);

// true

This will check every property on the object recursively to find the value. You can modify a little bit this function to return the name or path of the property that has this value.

Comments

-1

_.has() method is used to check whether the path is a direct property of the object or not. It returns true if the path exists, else it returns false.

var object = { 'a': { 'b': 2 } };
console.log(_.has(object, 'a.b')); 
console.log(_.has(object, ['a','b'])); 
console.log(_.has(object, ['a','b','c']));

Output: true true false

1 Comment

This solution requires the Lodash library which OP does not specify that he is using.
-1

Check the in

const car = { make: 'Honda', model: 'Accord', year: 1998 };

console.log('make' in car);
// Expected output: true

delete car.make;
if ('make' in car === false) {
  car.make = 'Suzuki';
}

console.log(car.make);
// Expected output: "Suzuki"

Source https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

1 Comment

Hi, we need to get value includes in object, not key.
-6

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

2 Comments

Please add your code to your answer as a text and not an image, see also How do I format my posts using Markdown or HTML?
Please transcribe the code in the image into text. Thanks in advance.
-7

This should be a simple check.

Example 1

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

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

2 Comments

This check the key not the value.
Thing will traverse the prototype chain and will probably work as expected !, for example var a = {};<br/>'hasOwnProperty' in a' //true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.