Checking if a key exists in a JavaScript object?

前端 未结 22 2210
礼貌的吻别
礼貌的吻别 2020-11-21 22:57

How do I check if a particular key exists in a JavaScript object or array?

If a key doesn\'t exist, and I try to access it, will it return false? Or throw an error?<

22条回答
  •  旧巷少年郎
    2020-11-21 23:52

    ES6 solution

    using Array#some and Object.keys. It will return true if given key exists in the object or false if it doesn't.

    var obj = {foo: 'one', bar: 'two'};
        
    function isKeyInObject(obj, key) {
        var res = Object.keys(obj).some(v => v == key);
        console.log(res);
    }
    
    isKeyInObject(obj, 'foo');
    isKeyInObject(obj, 'something');

    One-line example.

    console.log(Object.keys({foo: 'one', bar: 'two'}).some(v => v == 'foo'));

提交回复
热议问题