- How do I check if a property exists in an object/dictionary?
- JavaScript Key in Object – How to Check if an Object has a Key in JS
- Here’s an Interactive Scrim about How to Check if an Object Has a Key in JavaScript
- How to Check if an Object Has a key in JavaScript with the in Operator
- How to Check if an Object Has a key in JavaScript with the hasOwnProperty() Method
- Wrapping Up
- Как проверить существования ключа в объекте js?
- Похожие
- Подписаться на ленту
- Checking if a key exists in a JS object
- 9 Answers 9
How do I check if a property exists in an object/dictionary?
I’m iterating over an array of words and trying to stuff them in an object literal so I can assign the value of how many times those words occur to each word in the literal/dictionary. The problem is I need to check to make sure that word hasn’t already been added into my literal. I tried using in to check if the property exists in the literal but it’s throwing an error: Cannot use ‘in’ operator to search for ‘We’ in undefined Here’s problematic function: I commented the line that’s causing the problem
function wordCountDict(filename) < wordCount = <>; inputFile = fs.readFile( root + filename, 'utf8', function( error, data ) < if(error) < console.log('error: ', error) return false; >var words = data.split(" "); for (i in words) < if(words[i] in wordCount) < // This is where the problem occurs wordCount[words[i]]++; >else < wordCount[words[i]] = 1; >console.log(words[i]); > >); >
I’m coming from python and this was always the best/easiest way to achieve this, but javascript doesn’t seem to agree. How would I do this in JavaScript?
I can’t see how you’d get that error message unless you’re destroying the wordCount object before the asynchronous readFile callback has run.
There clearly is an object, and using in to check for keys in an object shouldn’t fail, and when it says the object is undefined, something else is going on here that we’re not seeing.
JavaScript Key in Object – How to Check if an Object has a Key in JS
Joel Olawanle
Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs.
As you can see in the image above, the key is the property, and each object value must have a key.
When interacting with objects, situations might arise that require you to check if a particular key exists. It is important to note that if you know a key exists that automatically means that a value exists. This value could be anything – even empty, null, or undefined.
In this article, we will learn the various methods to check if an object’s key exists in JavaScript.
Here’s an Interactive Scrim about How to Check if an Object Has a Key in JavaScript
In case you are in a rush, here are the two standard methods we can use to check:
// Using in operator 'key' in object // Using hasOwnProperty() method object.hasOwnProperty('key')
How to Check if an Object Has a key in JavaScript with the in Operator
You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain.
The syntax when using the in operator is:
Suppose we have an object which contains a user’s details:
We can check if a key exists with the in operator as seen below:
'name' in user; // Returns true 'hobby' in user; // Returns false 'age' in user; // Returns true
Note: The value before the in keyword should be of type string or symbol .
How to Check if an Object Has a key in JavaScript with the hasOwnProperty() Method
You can use the JavaScript hasOwnProperty() method to check if a specified object has the given property as its property. T
his method is pretty similar to the in operator. It takes in a string and will return true if the key exists in the object and false otherwise.
The syntax when using the hasOwnProperty() method is:
Suppose we have an object which contains a user’s details:
We can check if a key exists with the in operator as seen below:
user.hasOwnProperty('name'); // Returns true user.hasOwnProperty('hobby'); // Returns false user.hasOwnProperty('age'); // Returns true
Note: The value you pass into the hasOwnProperty() method should be of type string or symbol .
Since we now know that these methods exist, we can now use a condition to check and perform whatever operation we wish to perform:
if ("name" in user) < console.log("the key exists on the object"); >// Or if (user.hasOwnProperty("name"))
Wrapping Up
In this article, we have learned how to check if an object has a key using the two standard methods. The difference between the two methods is that Object.hasOwnProperty() looks for a key in an object alone while the in operator looks for the key in the object and its prototype chain.
There are other methods you can use, but at some point they might get too elaborate and aren’t that easy to understand. They also might fail when tested against certain conditions.
For example, we could use the optional chaining, so if a specified key does not exist, it will return undefined :
let user = < name: "John Doe", age: 40 >; console.log(user?.name); // Returns John Doe console.log(user?.hobby); // Returns undefined console.log(user?.age); // Returns 40
So we could create a condition that, when it’s not equal to undefined , it means the key exists:
As we said earlier, these methods fail when tested against some uncommon conditions. For example, in a situation when a particular key is set to «undefined», as seen below, the condition fails:
let user = < name: "John Doe", age: undefined >; console.log(user?.age); // Returns undefined
Another example when it works but gets elaborate is when we use the Object.keys() method alongside the some() method. This works but isn’t really easy to understand:
let user = < name: "John Doe", age: undefined >; const checkIfKeyExist = (objectName, keyName) => < let keyExist = Object.keys(objectName).some(key =>key === keyName); return keyExist; >; console.log(checkIfKeyExist(user, 'name')); // Returns true
In the code above, we retired all the keys as an array and then applied the some() method to test whether at least one element in the array passed the test. If it passes, it returns true , else false .
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.
Как проверить существования ключа в объекте js?
Также можно использовать оператор опциональной последовательности (optional chaining), доступный начиная с ECMAScript 2020:
Проверяем наличие ключа «c» в объекте «b», который является свойством объекта «a»
В этом случае оператор «?» проверяет наличие свойств «a», «b» и «c» в объекте, и если хотя бы один из них отсутствует, то результатом выражения будет undefined. Если все свойства существуют, то выражение вернет значение ключа «c».
Бывает так, что нам нужно проверить есть есть ли значение во вложенном объекте и если есть получить его значение, иначе вернуть значение по умолчанию например obj=< a:< b:'valueB'>, c:»valueC» > Нужно проверить есть ли obj.a.b и если есть вернуть valueB
check(strPath, value = null) < let iSValue = value; try < iSValue = eval(strPath); >catch (e) < iSValue = value; >return iSValue; >, console.log("check", this.check("obj.a.b", "defaultValue")); // вернет valueB console.log("check", this.check("obj.s.a.b", "defaultValue")); // вернет defaultValue console.log("check", this.check("obj.s.a.b")); // вернет null
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.25.43544
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Checking if a key exists in a JS object
True ;), shows that I don’t have a js background — started with the jQuery library right from the start, and I believe I need to learn the basics.
9 Answers 9
Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.
That’s not a jQuery object, it’s just an object.
You can use the hasOwnProperty method to check for a key:
@Fan_of_Martijn_Pieters i follow strict ESlint rule set. it is mentioned there as one of the rules.eslint.org/docs/rules/no-prototype-builtins
Downvoted because this does not work when detecting keys with a null value. For example, if the value of obj[«key1»] == null (so key1 exists in obj and its value is null), this will return a false result that key1 is not in obj.
var obj = < "key1" : "k1", "key2" : "k2", "key3" : "k3" >; if ("key1" in obj) console.log("has key1 in obj");
To access a child key of another key
var obj = < "key1": "k1", "key2": "k2", "key3": "k3", "key4": < "keyF": "kf" >>; if ("keyF" in obj.key4) console.log("has keyF in obj");
Above answers are good. But this is good too and useful.
!obj['your_key'] // if 'your_key' not in obj the result --> true
It’s good for short style of code special in if statements:
Note: If your key be equal to null or «» your «if» statement will be wrong.
obj = !obj['a'] // result ---> true !obj['b'] // result ---> true !obj['c'] // result ---> true !obj['d'] // result ---> false
So, best way for checking if a key exists in a obj is: ‘a’ in obj