检查JavaScript对象中是否存在键?

时间:2022-08-30 10:15:09

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

如何检查JavaScript对象或数组中是否存在某个键?

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

如果一个键不存在,我试图访问它,它会返回false吗?或者抛出一个错误?

16 个解决方案

#1


3015  

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

检查不确定性不是测试键是否存在的准确方法。如果键存在但值实际上没有定义,该怎么办?

var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!

You should instead use the in operator:

您应该使用in操作符:

"key" in obj // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:

如果你想检查一个键是否不存在,记得使用括号:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

或者,如果您想特别测试对象实例的属性(而不是继承属性),请使用hasOwnProperty:

obj.hasOwnProperty("key") // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark

对于未定义的hasOwnProperty和key的方法之间的性能比较,请参见这个基准

#2


215  

quick answer

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?

如何检查JavaScript对象或数组中是否存在特定的键?如果一个键不存在,我试图访问它,它会返回false吗?或者抛出一个错误?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

使用(关联的)数组样式或对象样式直接访问丢失的属性将返回一个未定义的常量。

The slow and reliable in operator and hasOwnProperty method

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

正如人们在这里已经提到的,您可以有一个具有与“未定义”常量相关联的属性的对象。

 var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

在这种情况下,您将不得不使用hasOwnProperty或In运算符来确定键是否真的在那里。但是,以什么价格呢?

so, I tell you...

所以,我告诉你……

in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

在操作符和hasOwnProperty中,“方法”是使用Javascript中的属性描述符机制(类似于Java语言中的Java反射)。

http://www.ecma-international.org/ecma-262/5.1/#sec-8.10

http://www.ecma-international.org/ecma-262/5.1/秒- 8.10

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each field’s name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

属性描述符类型用于解释命名属性的操作和具体化。属性描述符类型的值是由命名字段组成的记录,其中每个字段的名称是属性名,其值是8.6.1中指定的相应属性值。此外,任何字段都可能存在或不存在。

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster!

另一方面,调用对象方法或键将使用Javascript [[[[Get]]]机制。那要快得多!

benchmark

http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array

http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array

检查JavaScript对象中是否存在键?.

Using in operator
var result = "Impression" in array;

The result was

结果是

12,931,832 ±0.21% ops/sec      92% slower 
Using hasOwnProperty
var result = array.hasOwnProperty("Impression")

The result was

结果是

16,021,758 ±0.45% ops/sec     91% slower
Accessing elements directly (brackets style)
var result = array["Impression"] === undefined

The result was

结果是

168,270,439 ±0.13 ops/sec     0.02% slower 
Accessing elements directly (object style)
var result = array.Impression  === undefined;

The result was

结果是

168,303,172 ±0.20%     fastest

EDIT: What is the reason to assign to a property the undefined value?

That question puzzles me. In Javascript, there are at least two references for absent objects to avoid problems like this: null and undefined.

这个问题困惑我。在Javascript中,至少有两个引用用于缺席对象,以避免类似这样的问题:null和undefined。

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack a value.

null是表示任何对象值都故意不存在的原始值,或者简单地说,表示确认的值缺失。另一方面,未定义的是未知值(未定义)。如果有一个属性稍后将使用适当的值,请考虑使用null引用而不是无定义的引用,因为在初始时刻,该属性被确认为缺少一个值。

Compare:

比较:

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Advise

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

避免使用未定义值的对象。尽可能直接检查并使用null来初始化属性值。否则,使用in运算符或hasOwnProperty()方法。

EDIT: 12/04/2018 - NOT RELEVANT ANYMORE

As people have commented, modern versions of the Javascript engines (with firefox exception) has changed the approach for access properties. Current implementation is slower than the previous one for this particular case but difference between access key and object are neglectable.

正如人们所评论的,现代版本的Javascript引擎(firefox除外)已经改变了访问属性的方法。对于这个特殊情况,当前实现比以前的实现要慢,但是访问键和对象之间的差异是可以忽略的。

#3


113  

It will return undefined.

它将返回定义。

var aa = {hello: "world"};
alert( aa["hello"] );      // popup box with "world"
alert( aa["goodbye"] );    // popup box with "undefined"

undefined is a special constant value. So you can say, e.g.

无定义是一个特殊的常数。所以你可以说,例如。

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

This is probably the best way to check for missing keys. However, as is pointed out in a comment below, it's theoretically possible that you'd want to have the actual value be undefined. I've never needed to do this and can't think of a reason offhand why I'd ever want to, but just for the sake of completeness, you can use the in operator

这可能是检查丢失键的最好方法。但是,正如下面的注释所指出的,理论上您可能希望实际值没有定义。我从来都不需要这样做,也不能马上想到为什么我想要这样做,但是为了完整性起见,您可以使用in运算符

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}

#4


21  

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

被接受的答案指的是客体。注意使用数组上的in操作符查找数据而不是键:

("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?

要在数组中测试现有元素:查找项目是否在JavaScript数组中的最佳方法?

#5


19  

Three ways to check if a property is present in a javascript object:

检查javascript对象中是否存在属性的三种方法:

  1. !!obj.theProperty
    Will convert value to bool. returns TRUE for all but the 'false' value
  2. ! ! obj。属性将值转换为bool。返回除“false”值外的所有值为TRUE
  3. 'theProperty' in obj
    Will return true if the property exists, no matter its value (even empty)
  4. 如果属性存在,则obj中的“theProperty”将返回true,无论它的值是多少(甚至是空的)
  5. obj.hasOwnProperty('theProperty')
    Does not check the prototype chain. (since all objects have the 'toString' method, 1 and 2 will return true on it, while 3 can return false on it.)
  6. object . hasownproperty ('theProperty')没有检查原型链。(因为所有对象都有“toString”方法,所以1和2将返回true,而3将返回false。)

Reference:

参考:

http://book.mixu.net/node/ch5.html

http://book.mixu.net/node/ch5.html

#6


18  

"key" in obj

Is likely testing only object attribute values that are very different from array keys

是否可能只测试与数组键非常不同的对象属性值

#7


12  

If you are using underscore.js library then object/array operations become simple.

如果你使用下划线。然后对象/数组操作变得简单。

In your case _.has method can be used. Example:

在你的情况中_。有方法可以使用。例子:

yourArray = {age: "10"}

_.has(yourArray, "age")

returns true

返回true

But,

但是,

_.has(yourArray, "invalidKey")

returns false

返回false

#8


8  

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!

这个键存在(key, search)可以用来在对象或数组中轻松查找键!

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

只需将想要查找的密钥传递给它,然后搜索obj(对象或数组)就可以找到它。

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.

它非常可靠,在跨浏览器中运行良好。

#9


8  

Answer:

答:

if ("key" in myObj)
{
    console.log("key exists!");
}
else
{
    console.log("key doesn't exist!");
}

Explanation:

解释:

The in operator will check if the key exists in the object. If you checked if the value was undefined: if (myObj["key"] === 'undefined'), you could run into problems because a key could possibly exist in your object with the undefined value.

in操作符将检查键是否存在于对象中。如果您检查该值是否为undefined: If (myObj["key"] === 'undefined'),您可能会遇到问题,因为在对象中可能存在一个具有undefined值的键。

For that reason, it is much better practice to first use the in operator and then compare the value that is inside the key once you already know it exists.

由于这个原因,最好先使用in操作符,然后在知道键存在后再比较键内的值。

#10


3  

vanila js

香草香精js

yourObjName.hasOwnProperty(key) : true ? false;

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

如果您想检查对象在es2015中是否至少有一个属性

Object.keys(yourObjName).length : true ? false

#11


3  

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.

使用数组#一些和种。如果对象中存在给定的键,则返回true;如果不存在,则返回false。

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

#12


2  

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

The underscore.js way -

下划线。js方法-

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

_.has = function(obj, key) {
  return hasOwnProperty.call(obj, key);
};

#13


1  

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

假设您有一个对象“产品”和两个项目。如果想查看这个对象中是否已经存在id,可以使用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

#14


0  

For those which have lodash included in their project:
There is a lodash _.get method which tries to get "deep" keys:

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

获取对象路径上的值。如果未定义解析值,则返回默认值。

var object = { 'a': [{ 'b': { 'c': 3 } }] };

console.log(
  _.get(object, 'a[0].b.c'),           // => 3
  _.get(object, ['a', '0', 'b', 'c']), // => 3
  _.get(object, 'a.b.c'),              // => undefined 
  _.get(object, 'a.b.c', 'default')    // => 'default'
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.

这将有效地检查是否定义了该键(无论其深度有多深),并且不会抛出错误,如果未定义该键,可能会损害程序的流。

#15


0  

While this necessarily check if a key exists, it does check for the truthiness of a value. Which undefined and null fall under.

虽然这必须检查是否存在一个键,但它确实检查了一个值的真实性。未定义和null都归为。

Boolean(obj.foo)

布尔(obj.foo)

This solution works best for me because I use typescript, and using strings like so 'foo' in obj or obj.hasOwnProperty('foo') to check whether a key exists or not does not provide me with intellisense.

这个解决方案对我最有效,因为我使用了typescript,在obj或object . hasownproperty ('foo')中使用类似“foo”的字符串来检查一个键是否存在,不提供给我智能感知。

#16


0  

These example can demonstrate the differences between defferent ways. Hope it will help you to pick the right one for your needs:

这些例子可以说明不同的方法之间的区别。希望它能帮助你选择适合你需要的:

// Lets create object `a` using create function `A`
function A(){};
A.prototype.onProtDef=2;
A.prototype.onProtUndef=undefined;
var a=new A();
a.ownProp = 3;
a.ownPropUndef = undefined;

// Let's try different methods:

a.onProtDef; // 2
a.onProtUndef; // undefined
a.ownProp; // 3
a.ownPropUndef; // undefined
a.whatEver; // undefined
a.valueOf; // ƒ valueOf() { [native code] }

a.hasOwnProperty('onProtDef'); // false
a.hasOwnProperty('onProtUndef'); // false
a.hasOwnProperty('ownProp'); // true
a.hasOwnProperty('ownPropUndef'); // true
a.hasOwnProperty('whatEver'); // false
a.hasOwnProperty('valueOf'); // false

'onProtDef' in a; // true
'onProtUndef' in a; // true
'ownProp' in a; // true
'ownPropUndef' in a; // true
'whatEver' in a; // false
'valueOf' in a; // true (on the prototype chain - Object.valueOf)

Object.keys(a); // ["ownProp", "ownPropUndef"]

#1


3015  

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

检查不确定性不是测试键是否存在的准确方法。如果键存在但值实际上没有定义,该怎么办?

var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!

You should instead use the in operator:

您应该使用in操作符:

"key" in obj // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:

如果你想检查一个键是否不存在,记得使用括号:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

或者,如果您想特别测试对象实例的属性(而不是继承属性),请使用hasOwnProperty:

obj.hasOwnProperty("key") // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark

对于未定义的hasOwnProperty和key的方法之间的性能比较,请参见这个基准

#2


215  

quick answer

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?

如何检查JavaScript对象或数组中是否存在特定的键?如果一个键不存在,我试图访问它,它会返回false吗?或者抛出一个错误?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

使用(关联的)数组样式或对象样式直接访问丢失的属性将返回一个未定义的常量。

The slow and reliable in operator and hasOwnProperty method

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

正如人们在这里已经提到的,您可以有一个具有与“未定义”常量相关联的属性的对象。

 var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

在这种情况下,您将不得不使用hasOwnProperty或In运算符来确定键是否真的在那里。但是,以什么价格呢?

so, I tell you...

所以,我告诉你……

in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

在操作符和hasOwnProperty中,“方法”是使用Javascript中的属性描述符机制(类似于Java语言中的Java反射)。

http://www.ecma-international.org/ecma-262/5.1/#sec-8.10

http://www.ecma-international.org/ecma-262/5.1/秒- 8.10

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each field’s name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

属性描述符类型用于解释命名属性的操作和具体化。属性描述符类型的值是由命名字段组成的记录,其中每个字段的名称是属性名,其值是8.6.1中指定的相应属性值。此外,任何字段都可能存在或不存在。

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster!

另一方面,调用对象方法或键将使用Javascript [[[[Get]]]机制。那要快得多!

benchmark

http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array

http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array

检查JavaScript对象中是否存在键?.

Using in operator
var result = "Impression" in array;

The result was

结果是

12,931,832 ±0.21% ops/sec      92% slower 
Using hasOwnProperty
var result = array.hasOwnProperty("Impression")

The result was

结果是

16,021,758 ±0.45% ops/sec     91% slower
Accessing elements directly (brackets style)
var result = array["Impression"] === undefined

The result was

结果是

168,270,439 ±0.13 ops/sec     0.02% slower 
Accessing elements directly (object style)
var result = array.Impression  === undefined;

The result was

结果是

168,303,172 ±0.20%     fastest

EDIT: What is the reason to assign to a property the undefined value?

That question puzzles me. In Javascript, there are at least two references for absent objects to avoid problems like this: null and undefined.

这个问题困惑我。在Javascript中,至少有两个引用用于缺席对象,以避免类似这样的问题:null和undefined。

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack a value.

null是表示任何对象值都故意不存在的原始值,或者简单地说,表示确认的值缺失。另一方面,未定义的是未知值(未定义)。如果有一个属性稍后将使用适当的值,请考虑使用null引用而不是无定义的引用,因为在初始时刻,该属性被确认为缺少一个值。

Compare:

比较:

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Advise

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

避免使用未定义值的对象。尽可能直接检查并使用null来初始化属性值。否则,使用in运算符或hasOwnProperty()方法。

EDIT: 12/04/2018 - NOT RELEVANT ANYMORE

As people have commented, modern versions of the Javascript engines (with firefox exception) has changed the approach for access properties. Current implementation is slower than the previous one for this particular case but difference between access key and object are neglectable.

正如人们所评论的,现代版本的Javascript引擎(firefox除外)已经改变了访问属性的方法。对于这个特殊情况,当前实现比以前的实现要慢,但是访问键和对象之间的差异是可以忽略的。

#3


113  

It will return undefined.

它将返回定义。

var aa = {hello: "world"};
alert( aa["hello"] );      // popup box with "world"
alert( aa["goodbye"] );    // popup box with "undefined"

undefined is a special constant value. So you can say, e.g.

无定义是一个特殊的常数。所以你可以说,例如。

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

This is probably the best way to check for missing keys. However, as is pointed out in a comment below, it's theoretically possible that you'd want to have the actual value be undefined. I've never needed to do this and can't think of a reason offhand why I'd ever want to, but just for the sake of completeness, you can use the in operator

这可能是检查丢失键的最好方法。但是,正如下面的注释所指出的,理论上您可能希望实际值没有定义。我从来都不需要这样做,也不能马上想到为什么我想要这样做,但是为了完整性起见,您可以使用in运算符

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}

#4


21  

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

被接受的答案指的是客体。注意使用数组上的in操作符查找数据而不是键:

("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?

要在数组中测试现有元素:查找项目是否在JavaScript数组中的最佳方法?

#5


19  

Three ways to check if a property is present in a javascript object:

检查javascript对象中是否存在属性的三种方法:

  1. !!obj.theProperty
    Will convert value to bool. returns TRUE for all but the 'false' value
  2. ! ! obj。属性将值转换为bool。返回除“false”值外的所有值为TRUE
  3. 'theProperty' in obj
    Will return true if the property exists, no matter its value (even empty)
  4. 如果属性存在,则obj中的“theProperty”将返回true,无论它的值是多少(甚至是空的)
  5. obj.hasOwnProperty('theProperty')
    Does not check the prototype chain. (since all objects have the 'toString' method, 1 and 2 will return true on it, while 3 can return false on it.)
  6. object . hasownproperty ('theProperty')没有检查原型链。(因为所有对象都有“toString”方法,所以1和2将返回true,而3将返回false。)

Reference:

参考:

http://book.mixu.net/node/ch5.html

http://book.mixu.net/node/ch5.html

#6


18  

"key" in obj

Is likely testing only object attribute values that are very different from array keys

是否可能只测试与数组键非常不同的对象属性值

#7


12  

If you are using underscore.js library then object/array operations become simple.

如果你使用下划线。然后对象/数组操作变得简单。

In your case _.has method can be used. Example:

在你的情况中_。有方法可以使用。例子:

yourArray = {age: "10"}

_.has(yourArray, "age")

returns true

返回true

But,

但是,

_.has(yourArray, "invalidKey")

returns false

返回false

#8


8  

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!

这个键存在(key, search)可以用来在对象或数组中轻松查找键!

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

只需将想要查找的密钥传递给它,然后搜索obj(对象或数组)就可以找到它。

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.

它非常可靠,在跨浏览器中运行良好。

#9


8  

Answer:

答:

if ("key" in myObj)
{
    console.log("key exists!");
}
else
{
    console.log("key doesn't exist!");
}

Explanation:

解释:

The in operator will check if the key exists in the object. If you checked if the value was undefined: if (myObj["key"] === 'undefined'), you could run into problems because a key could possibly exist in your object with the undefined value.

in操作符将检查键是否存在于对象中。如果您检查该值是否为undefined: If (myObj["key"] === 'undefined'),您可能会遇到问题,因为在对象中可能存在一个具有undefined值的键。

For that reason, it is much better practice to first use the in operator and then compare the value that is inside the key once you already know it exists.

由于这个原因,最好先使用in操作符,然后在知道键存在后再比较键内的值。

#10


3  

vanila js

香草香精js

yourObjName.hasOwnProperty(key) : true ? false;

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

如果您想检查对象在es2015中是否至少有一个属性

Object.keys(yourObjName).length : true ? false

#11


3  

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.

使用数组#一些和种。如果对象中存在给定的键,则返回true;如果不存在,则返回false。

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

#12


2  

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

The underscore.js way -

下划线。js方法-

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

_.has = function(obj, key) {
  return hasOwnProperty.call(obj, key);
};

#13


1  

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

假设您有一个对象“产品”和两个项目。如果想查看这个对象中是否已经存在id,可以使用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

#14


0  

For those which have lodash included in their project:
There is a lodash _.get method which tries to get "deep" keys:

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

获取对象路径上的值。如果未定义解析值,则返回默认值。

var object = { 'a': [{ 'b': { 'c': 3 } }] };

console.log(
  _.get(object, 'a[0].b.c'),           // => 3
  _.get(object, ['a', '0', 'b', 'c']), // => 3
  _.get(object, 'a.b.c'),              // => undefined 
  _.get(object, 'a.b.c', 'default')    // => 'default'
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.

这将有效地检查是否定义了该键(无论其深度有多深),并且不会抛出错误,如果未定义该键,可能会损害程序的流。

#15


0  

While this necessarily check if a key exists, it does check for the truthiness of a value. Which undefined and null fall under.

虽然这必须检查是否存在一个键,但它确实检查了一个值的真实性。未定义和null都归为。

Boolean(obj.foo)

布尔(obj.foo)

This solution works best for me because I use typescript, and using strings like so 'foo' in obj or obj.hasOwnProperty('foo') to check whether a key exists or not does not provide me with intellisense.

这个解决方案对我最有效,因为我使用了typescript,在obj或object . hasownproperty ('foo')中使用类似“foo”的字符串来检查一个键是否存在,不提供给我智能感知。

#16


0  

These example can demonstrate the differences between defferent ways. Hope it will help you to pick the right one for your needs:

这些例子可以说明不同的方法之间的区别。希望它能帮助你选择适合你需要的:

// Lets create object `a` using create function `A`
function A(){};
A.prototype.onProtDef=2;
A.prototype.onProtUndef=undefined;
var a=new A();
a.ownProp = 3;
a.ownPropUndef = undefined;

// Let's try different methods:

a.onProtDef; // 2
a.onProtUndef; // undefined
a.ownProp; // 3
a.ownPropUndef; // undefined
a.whatEver; // undefined
a.valueOf; // ƒ valueOf() { [native code] }

a.hasOwnProperty('onProtDef'); // false
a.hasOwnProperty('onProtUndef'); // false
a.hasOwnProperty('ownProp'); // true
a.hasOwnProperty('ownPropUndef'); // true
a.hasOwnProperty('whatEver'); // false
a.hasOwnProperty('valueOf'); // false

'onProtDef' in a; // true
'onProtUndef' in a; // true
'ownProp' in a; // true
'ownPropUndef' in a; // true
'whatEver' in a; // false
'valueOf' in a; // true (on the prototype chain - Object.valueOf)

Object.keys(a); // ["ownProp", "ownPropUndef"]