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

后端 未结 15 2480
不思量自难忘°
不思量自难忘° 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:10

    You can use the Array method .some:

    var exists = Object.keys(obj).some(function(k) {
        return obj[k] === "test1";
    });
    
    0 讨论(0)
  • 2020-11-29 20:10
    if( myObj.hasOwnProperty('key') && myObj['key'] === value ){
        ...
    }
    
    0 讨论(0)
  • 2020-11-29 20:13

    Use a for...in loop:

    for (let k in obj) {
        if (obj[k] === "test1") {
            return true;
        }
    }
    
    0 讨论(0)
  • 2020-11-29 20:15

    Shortest ES6+ one liner:

    let exists = Object.values(obj).includes("test1");
    
    0 讨论(0)
  • 2020-11-29 20:16

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

    0 讨论(0)
  • 2020-11-29 20:17

    For a one-liner, I would say:

    exist = Object.values(obj).includes("test1");
    console.log(exist);
    
    0 讨论(0)
提交回复
热议问题