How do you check if a key exists in an array javascript?

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?

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?

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].

//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!

Benchmark

//jsben.ch/HaHQt

.

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.

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[].

Advice

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.

EDIT: 12/04/2018 - NOT RELEVANT ANYMORE

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.

In JavaScript an object is found to be in the form of key value pairs. The keys of the objects are known as properties of the given object and is represented using a string. The property of the object can have a value which can be of any data type.

For example, if an employee object is created then it has the properties like employee name, employee id, employee age, salary etc. These are the properties of the employee object which are called keys. The values of these properties will be different for different employees.

In case of array, the key is the index and there will be a value at the index if the given index exists.

To check for the existence of key for an object or array in JavaScript can be done by using some functions and operators.

Using in operator

The in operator checks for the given key only for an object and returns a Boolean result i.e., ‘true’ if the object has the given key or ‘false’ if it doesn’t accordingly.

Syntax

The syntax of in operator is shown below.

For objects:
key in objectName //returns true if the object has the [key]objectProperty

Example

This example demonstrates the usage of in operator to check if key exists in Object −

let employee = { firstName: 'Mohammed', lastName: 'Abdul Rawoof', id : 1000, designation: 'Intern Software Engineer', salary : 18000 }; console.log["The given employee details are: ",employee] console.log["Is firstName present in employee:",'firstName' in employee]; console.log["Is employee age present in employee:",'age' in employee] console.log["Is 18000 present in employee:", 18000 in employee]

In operator for arrays

In arrays, if a value exists at the given index, then the in operator will return true or else it returns false.

Syntax

For arrays:
Index in arrayName //returns true if the given index has a value

Example

This example demonstrates how to check if a key exists in arrays using in operator −

function getKeyArr[a,indx]{ console.log["The given array with its length is:",a,a.length] if[indx in a]{ console.log["The array has a key at the given index",indx] } else{ console.log["The array doesn't have a key at the given index",indx," as its array length is:",a.length] } } console.log["Checking the existance of a key in an array using hasOwnProperty[]"] getKeyArr[[12,56,33,2,7],4] getKeyArr[[12,56,33,2,7],8] getKeyArr[[1,2,4,53,36,7,83,90,45,28,19],16]

Using hasOwnProperty[] function

The function hasOwnProperty[] will check for the existence of a key in the given object and returns true if the key is present or else it returns false. This function takes the key of the object as the parameter and returns the Boolean result accordingly.

Syntax

This is the syntax for the hasOwnProperty[] function.

For object:
objectName.hasOwnPropert[key] //key is object property.

Example 3

This example demonstrates the usage of hasOwnProperty[] to check for keys in object −

let employee = { emp_name: 'Abdul Rawoof', emp_id: 1000, role: 'Software Engineer', salary: 18000 }; console.log["The given employee details are:", employee] console.log["Checking the keys present in an object using hasOwnProperty:"] function getEmpDet[str]{ if[employee.hasOwnProperty[str]]{ console.log["The given employee object has",str] } else{ console.log["The given employee object doesn't have",str] } } getEmpDet['emp_id'] getEmpDet['salary'] getEmpDet['designation']

hasOwnProperty[] for Arrays

In arrays, if a value exists at the given index, then the in operator will return true or else it returns false. Whereas the hasOwnProperty[] method can check if an index is available but not empty in the array.

Syntax

The syntax of hasOwnProperty[] for arrays is seen below.

arrayName.hasOwnProperty[index]

Example

This example demonstrates how to check if a key exists in arrays using hasOwnProperty −

function getKeyArr[a,indx]{ console.log["The given array with its length is:",a,a.length] if[a.hasOwnProperty[indx]]{ console.log["The array has a key at the given index",indx] } else{ console.log["The array doesn't have a key at the given index",indx," as its array length is:",a.length] } } console.log["Checking the existance of a key in an array using hasOwnProperty[]"] getKeyArr[[12,56,33,2,7],4] getKeyArr[[12,56,33,2,7],8] getKeyArr[[1,2,4,53,36,7,83,90,45,28,19],16]

Updated on 26-Aug-2022 11:59:20

  • Related Questions & Answers
  • How to check whether a key exist in JavaScript object or not?
  • JavaScript: How to check whether an array includes a particular value or not?
  • How to check whether multiple values exist within a JavaScript array
  • Check whether field exist in MongoDB or not?
  • How to check whether a stored procedure exist in MySQL?
  • Check whether a SortedList object contains a specific key in C#?
  • Check whether a Hashtable contains a specific key or not in C#
  • How to check in C# whether the string array contains a particular work in a string array?
  • How to check whether an array is a true array in JavaScript?
  • How to check whether a number is finite or not in JavaScript?
  • How to check whether a NaN is a NaN or not in JavaScript?
  • Check if a particular key exists in Java LinkedHashMap
  • Check whether property exists in object or class with PHP
  • How to check whether a value is a safe integer or not in JavaScript?
  • How to know whether an object is sealed or not in JavaScript?

How do I check if a key is present in an array of objects?

indexOf[] method. That method would return the numerical index of a specified value [an object key, in our case] if that value is indeed present in the array upon which indexOf[] is called [or it will return -1 if the specified value/key does not exist within the array].

How do you check if an item is present in an array in JavaScript?

You can use the includes[] method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check if a key exists in an object in JavaScript?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty[] method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

How do you check if a key value pair exists in an object JavaScript?

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.

Chủ Đề