Checking if a key exists in a JavaScript object?

2018-12-31 04:04发布

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?

19条回答
孤独寂梦人
2楼-- · 2018-12-31 04:28

We can use - hasOwnProperty.call(obj, key);

The underscore.js way -

if(_.has(this.options, 'login')){
  //key 'login' exists in this.options 
}

_.has = function(obj, key) {
  return hasOwnProperty.call(obj, key);
};
查看更多
素衣白纱
3楼-- · 2018-12-31 04:28

This is an old question but I guess never to late to give an answer.

Imagine that you have an object "products" and two items. If you want to see if id already exists in this object you can use find()

products = [
    {
        "id": 1,
        "name": "Name 1"
    },
    {
        "id": 2,
        "name": "Name 2"
    },
  ]

  item1 = 
    {
        "id": 3,
        "name": "Name 3",
    }



  item2 = 
    {
        "id": 1,
        "name": "Name 1",
    }



  if(products.find(x => x.id === item1.id)){
    console.log('id is in products');
  }else {
    console.log('id is not in products');
  }
  if(products.find(x => x.id === item2.id)){
    console.log('id is in products');
  }else {
    console.log('id is not in products');
  }

log:

id is not in products
id is in products
查看更多
情到深处是孤独
4楼-- · 2018-12-31 04:30

New awesome solution with JavaScript Destructuring:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

Do check other use of JavaScript Destructuring

查看更多
浪荡孟婆
5楼-- · 2018-12-31 04:31

Here's a helper function I find quite useful

This keyExists(key, search) can be used to easily lookup a key within objects or arrays!

Just pass it the key you want to find, and search obj (the object or array) you want to find it in.

function keyExists(key, search) {
    if (!search || (search.constructor !== Array && search.constructor !== Object)) {
        return false;
    }
    for (var i = 0; i < search.length; i++) {
        if (search[i] === key) {
            return true;
        }
    }
    return key in search;
}

How to use it:

Searching for keys in Arrays

keyExists('apple', ['apple', 'banana', 'orange']); // true
keyExists('fruit', ['apple', 'banana', 'orange']); // false

Searching for keys in Objects

keyExists('age', {'name': 'Bill', 'age': 29 }); // true
keyExists('title', {'name': 'Jason', 'age': 29 }); // false

It's been pretty reliable and works well cross-browser.

查看更多
临风纵饮
6楼-- · 2018-12-31 04:31

vanila js

yourObjName.hasOwnProperty(key) : true ? false;

If you want to check if the object has at least one property in es2015

Object.keys(yourObjName).length : true ? false
查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 04:31

The accepted answer refers to Object. Beware using the in operator on Array to find data instead of keys:

("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)

To test existing elements in an Array: Best way to find if an item is in a JavaScript array?

查看更多
登录 后发表回答