How to Check if Key Exists in JavaScript Object/Array

An object in JavaScript is an unordered collection of key-value pairs ( key: value ). Each key is known as a property, and is a string representing a property name. If a non-string is given as the key, its stringified representation will be used. A property's value can be of any data type that fits the property conceptually — a string, a number, an array, or even a function.
An array, on the other hand, is a sorted set of values. Each value is referred to as an element, which is identified by a numerical index. An array can include values of almost any type. For example, it can store items like integers, strings, booleans, functions, etc. JavaScript arrays are also not restricted to a single type, meaning a given array can contain multiple different types within it.
When working in JavaScript, you might at a particular point in time need to determine if a key exists in a given object or array.
In this article, we will see the various methods which we could use to check if a particular key exists in a JavaScript object/array.
Using the in Operator
The in operator in JavaScript is used to determine if a certain property exists in an object or its inherited properties (also known as its prototype chain). If the provided property exists, the in operator returns true.
Checking an Object
Checking an Array
Since we demonstrated that the JavaScript in operator can be used with objects, you may be asking if it can also be used with arrays. In JavaScript, everything is an instance of the Object type (except for primitives), so arrays also support the in operator.
Let's confirm if it's an instance of the Object type using the instanceof operator:
Now, back to using the in operator:
This will also return true for method properties on an array type, of which the number array is an instance.
Using the hasOwnProperty() Method
In JavaScript, the hasOwnProperty() function is used to determine whether the object has the supplied property as its own property. This is important for determining if the attribute was inherited by the object rather than being its own.
Checking an Object
Checking an Array
You might begin to wonder if this would work for arrays. As we established earlier, an array is actually a prototype (instance) of the Object type, therefore it also has this method available to it.
Using the Object.key() Method
The static method Object.key generates and returns an array whose components are strings of the names (keys) of an object's properties. This may be used to loop through the object's keys, which we can then use to verify if any match a certain key in the object.
Using the some() Method
some() is a JavaScript method that tests a callback function on all the elements of the calling array and returns true if the callback function returns true for any of them.
Using some() for Objects
We could also customize this into a reusable function:
Using some() for an Array
Again, just like with the object, we could also make use of a similar customized reusable function to check a value's existence in an array:
Using the indexOf() Method
JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.
Using indexOf() for an Object
The Object type in JavaScript does not actually support the indexOf method, since its properties/keys do not inherently have indexed positions in the object. Instead, we can get the object's keys as an array and then check the existence of a key using the indexOf method:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Keep in mind that JavaScript objects do not always preserve key order, so the index returned may not be as meaningful as in arrays. In this case, the index should primarily be used to determine just the existence of a key.
Here is an example of using this in a utility function:
Using indexOf() for an Array
As we saw in the previous example, arrays do support the indexOf method, unlike objects. To use it, pass the value of the item you're looking for to indexOf , which will then return the position of that value if it exists in the array:
Conclusion
In this article, we have seen all of the possible ways in which we could check if a key or item exists in a JavaScript object/array. We show how to make use of the in operator, hasOwnProperty() method, and some method. We also saw how JS objects and arrays are similar in that arrays inherit from objects, and thus contain many of the same methods.
Object.hasOwn()
The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false .
Note: Object.hasOwn() is intended as a replacement for Object.prototype.hasOwnProperty() .
Try it
Syntax
Parameters
The JavaScript object instance to test.
The String name or Symbol of the property to test.
Return value
true if the specified object has directly defined the specified property. Otherwise false
Description
The Object.hasOwn() method returns true if the specified property is a direct property of the object — even if the property value is null or undefined . The method returns false if the property is inherited, or has not been declared at all. Unlike the in operator, this method does not check for the specified property in the object’s prototype chain.
It is recommended over Object.prototype.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.
Examples
Using hasOwn to test for a property’s existence
The following code shows how to determine whether the example object contains a property named prop .
Direct vs. inherited properties
The following example differentiates between direct properties and properties inherited through the prototype chain:
Iterating over the properties of an object
To iterate over the enumerable properties of an object, you should use:
But if you need to use for. in , you can use Object.hasOwn() to skip the inherited properties:
Checking if an Array index exists
The elements of an Array are defined as direct properties, so you can use hasOwn() method to check whether a particular index exists:
Problematic cases for hasOwnProperty
This section demonstrates that hasOwn() is immune to the problems that affect hasOwnProperty . Firstly, it can be used with objects that have reimplemented hasOwnProperty() :
Проверка наличия ключа в объекте в JavaScript
При работе с JavaScript часто возникает необходимость проверить, есть ли определенный ключ в объекте. Это может быть полезно в различных ситуациях, например, при работе с JSON-объектами, полученными из внешнего источника, или при создании словарей и хэш-таблиц.
Например, есть объект person , который может содержать разные свойства:
Необходимо проверить, есть ли у этого объекта свойство profession .
В JavaScript для этого есть несколько способов.
Способ 1: сравнение с undefined
Этот способ работает, потому что если ключа нет в объекте, то обращение к нему вернет значение undefined .
Способ 2: сравнение с null
Этот способ не совсем корректен, так как null и undefined — это разные типы данных. Хотя в JavaScript null == undefined вернет true , лучше всегда использовать строгое сравнение ( === ), которое учитывает типы данных.
Способ 3: просто проверка ключа
Этот способ может быть полезен, но он может привести к неожиданным результатам, если значение ключа является «ложным» ( false , 0 , «» , null , undefined , NaN ). В этом случае проверка вернет false , даже если ключ есть в объекте.
Способ 4: использование оператора in
Этот способ является наиболее предпочтительным и безопасным способом проверить наличие ключа в объекте.
Обратите внимание, что в операторе in ключ указывается в кавычках, так как это строка. Если ключ — это переменная, то кавычки не нужны.
В заключение, при проверке наличия ключа в объекте в JavaScript рекомендуется использовать оператор in , чтобы избежать неожиданных результатов.
Проверка, существует ли ключ в объекте JavaScript?
Как проверить, существует ли конкретный ключ в объекте или массиве JavaScript?
Если ключ не существует, и я пытаюсь получить к нему доступ, вернет ли он false? Или выбросить ошибку?
20 ответов
Проверка неопределенности не является точным способом проверки наличия ключа. Что делать, если ключ существует, но значение фактически undefined ?
Вместо этого вы должны использовать оператор in :
Если вы хотите проверить, нет ли ключа, не забудьте использовать скобки:
Или, если вы хотите особенно проверить свойства экземпляра объекта (и не наследуемые свойства), используйте hasOwnProperty :
Для сравнения производительности между методами, которые находятся in , hasOwnProperty и ключ не undefined , см. Этот тест
быстрый ответ
Как проверить, существует ли какой-либо конкретный ключ в объекте или массиве JavaScript? Если ключ не существует, и я пытаюсь получить к нему доступ, он вернет false? Или выбросить ошибку?
Доступ непосредственно к отсутствующему свойству с использованием (ассоциативного) стиля массива или стиля объекта возвращает неопределенную константу.
Медленный и надежный метод оператора и hasOwnProperty
Как уже упоминалось здесь, у вас может быть объект со свойством, связанным с константой «undefined».
В этом случае вам нужно будет использовать hasOwnProperty или у оператора, чтобы узнать, действительно ли ключ. Но, но по какой цене?
так, я говорю вам.
in operator и hasOwnProperty — это «методы», которые используют механизм дескриптора свойства в Javascript (аналогично отражению Java на языке Java).
Тип дескриптора свойства используется для объяснения манипуляций и переопределения атрибутов именованного свойства. Значения типа дескриптора свойства — это записи, состоящие из именованных полей, где каждое имя поля является именем атрибута, а его значение является соответствующим значением атрибута, как указано в 8.6.1. Кроме того, любое поле может присутствовать или отсутствовать.
С другой стороны, вызов метода объекта или ключа будет использовать механизм Javascript [[Get]]. Это намного быстрее!
эталонный тест
.
Использование в операторе
Доступ к элементам напрямую (стиль скобок)
Доступ к элементам напрямую (стиль объекта)
EDIT: В чем причина присвоения свойства undefined значение?
Этот вопрос меня озадачивает. В Javascript существует не менее двух ссылок для отсутствующих объектов, чтобы избежать таких проблем: null и undefined .
null — это примитивное значение, которое представляет собой намеренное отсутствие какого-либо значения объекта или в короткие сроки подтвержденное отсутствие ценности. С другой стороны, undefined — неизвестное значение (не определено). Если есть свойство, которое будет использоваться позже с надлежащим значением, рассмотрите использование null ссылки вместо undefined потому что в начальный момент свойство подтверждается отсутствием значения.
Консультировать
Избегайте объектов с undefined значениями. Проверяйте, когда это возможно, по возможности и используйте значение null для инициализации значений свойств. В противном случае используйте метод slow in operator или hasOwnProperty() .
EDIT: 12/04/2018 — НЕ СООТВЕТСТВУЕТ ЛЮБОЙ
Как отмечают люди, современные версии движков Javascript (с исключением firefox) изменили подход к свойствам доступа. Текущая реализация медленнее предыдущей для данного конкретного случая, но разница между ключом доступа и объектом пренебрежимо мала.