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

后端 未结 15 2574
不思量自难忘°
不思量自难忘° 2020-11-29 19:38

I have an object in JavaScript:

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

How do I check that te

15条回答
  •  被撕碎了的回忆
    2020-11-29 20:06

    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

提交回复
热议问题