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?
This question is related to
javascript
arrays
object
lodash
included in their project: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 } }] };_x000D_
_x000D_
console.log(_x000D_
_.get(object, 'a[0].b.c'), // => 3_x000D_
_.get(object, ['a', '0', 'b', 'c']), // => 3_x000D_
_.get(object, 'a.b.c'), // => undefined _x000D_
_.get(object, 'a.b.c', 'default') // => 'default'_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
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.
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);
};
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"]
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?
const object1 = {
a: 'something',
b: 'something',
c: 'something'
};
const key = 's';
// Object.keys(object1) will return array of the object keys ['a', 'b', 'c']
Object.keys(object1).indexOf(key) === -1 ? 'the key is not there' : 'yep the key is exist';
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
But,
_.has(yourArray, "invalidKey")
returns false
Three ways to check if a property is present in a javascript object:
!!obj.theProperty
true
for all but the false
valuetheProperty
' in objobj.hasOwnProperty('theProperty')
toString
method, 1 and 2 will return true on it, while 3 can return false on it.)Reference:
yourArray.indexOf(yourArrayKeyName) > -1
fruit = ['apple', 'grapes', 'banana']
fruit.indexOf('apple') > -1
true
fruit = ['apple', 'grapes', 'banana']
fruit.indexOf('apple1') > -1
false
In 'array' world we can look on indexes as some kind of keys. What is surprising the in
operator (which is good choice for object) also works with arrays. The returned value for non-existed key is undefined
let arr = ["a","b","c"]; // we have indexes: 0,1,2_x000D_
delete arr[1]; // set 'empty' at index 1_x000D_
arr.pop(); // remove last item_x000D_
_x000D_
console.log(0 in arr, arr[0]);_x000D_
console.log(1 in arr, arr[1]);_x000D_
console.log(2 in arr, arr[2]);
_x000D_
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
Optional Chaining operator can also be used for this
?.
sorce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
If you want to check for any key at any depth on an object and account for falsey values consider this line for a utility function:
var keyExistsOn = (o, k) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;
Results
var obj = {
test: "",
locals: {
test: "",
test2: false,
test3: NaN,
test4: 0,
test5: undefined,
auth: {
user: "hw"
}
}
}
keyExistsOn(obj, "")
> false
keyExistsOn(obj, "locals.test")
> true
keyExistsOn(obj, "locals.test2")
> true
keyExistsOn(obj, "locals.test3")
> true
keyExistsOn(obj, "locals.test4")
> true
keyExistsOn(obj, "locals.test5")
> true
keyExistsOn(obj, "sdsdf")
false
keyExistsOn(obj, "sdsdf.rtsd")
false
keyExistsOn(obj, "sdsdf.234d")
false
keyExistsOn(obj, "2134.sdsdf.234d")
false
keyExistsOn(obj, "locals")
true
keyExistsOn(obj, "locals.")
false
keyExistsOn(obj, "locals.auth")
true
keyExistsOn(obj, "locals.autht")
false
keyExistsOn(obj, "locals.auth.")
false
keyExistsOn(obj, "locals.auth.user")
true
keyExistsOn(obj, "locals.auth.userr")
false
keyExistsOn(obj, "locals.auth.user.")
false
keyExistsOn(obj, "locals.auth.user")
true
Also see this NPM package: https://www.npmjs.com/package/has-deep-value
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?
Accessing directly a missing property using (associative) array style or object style will return an undefined constant.
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?
so, I tell you...
in operator and hasOwnProperty are "methods" that use the Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).
http://www.ecma-international.org/ecma-262/5.1/#sec-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.
On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is a far way faster!
http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array
.
Using in operatorvar 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
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
.
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 an 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 value.
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[].
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.
As people have commented, modern versions of the Javascript engines (with firefox exception) have changed the approach for access properties. The current implementation is slower than the previous one for this particular case but the difference between access key and object is neglectable.
A fast and easy solution is to convert your object to json then you will be able to do this easy task:
const allowed = {
'/login' : '',
'/register': '',
'/resetpsw': ''
};
console.log('/login' in allowed); //returns true
If you use an array the object key will be converted to integers ex 0,1,2,3 etc. therefore, it will always be false
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.
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.
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'};_x000D_
_x000D_
function isKeyInObject(obj, key) {_x000D_
var res = Object.keys(obj).some(v => v == key);_x000D_
console.log(res);_x000D_
}_x000D_
_x000D_
isKeyInObject(obj, 'foo');_x000D_
isKeyInObject(obj, 'something');
_x000D_
One-line example.
console.log(Object.keys({foo: 'one', bar: 'two'}).some(v => v == 'foo'));
_x000D_
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
The easiest way to check is
"key" in object
for example:
var obj = {
a: 1,
b: 2,
}
"a" in obj // true
"c" in obj // false
Return value as true implies that key exists in the object.
While this doesn't necessarily check if a key exists, it does check for the truthiness of a value. Which undefined
and null
fall under.
Boolean(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.
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) {_x000D_
if (!search || (search.constructor !== Array && search.constructor !== Object)) {_x000D_
return false;_x000D_
}_x000D_
for (var i = 0; i < search.length; i++) {_x000D_
if (search[i] === key) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
return key in search;_x000D_
}_x000D_
_x000D_
// How to use it:_x000D_
// Searching for keys in Arrays_x000D_
console.log(keyExists('apple', ['apple', 'banana', 'orange'])); // true_x000D_
console.log(keyExists('fruit', ['apple', 'banana', 'orange'])); // false_x000D_
_x000D_
// Searching for keys in Objects_x000D_
console.log(keyExists('age', {'name': 'Bill', 'age': 29 })); // true_x000D_
console.log(keyExists('title', {'name': 'Jason', 'age': 29 })); // false
_x000D_
It's been pretty reliable and works well cross-browser.
"key" in obj
Is likely testing only object attribute values that are very different from array keys
It will return undefined
.
var aa = {hello: "world"};_x000D_
alert( aa["hello"] ); // popup box with "world"_x000D_
alert( aa["goodbye"] ); // popup box with "undefined"
_x000D_
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
// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
// do something
}
Source: Stackoverflow.com