Node JS Check if Array Key Exists Example

12-Aug-2022

.

Admin

Node JS Check if Array Key Exists Example

Hi Friends,

Today, node js check if array key exists example is our main topic. I would like to share with you check if array key exists node.js. I would like to show you how to check if array key exists in node js. This article goes in detailed on how to check if array key exists using in operator in node js.

There are many ways to use node js check if array key exists in node js. I will give you two examples using in operator and hasOwnProperty(). You can easily check key exists if statement. in operator can be used with objects, you may be asking if it can also be used with arrays. The hasOwnProperty() method returns true if the specified key is in the object, otherwise it returns false.

let's see below a simple example with output:

Install Node JS


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Example: 1

index.js

// program to check if a key exists

person = {

id: 1,

name: 'Piyush',

age: 23

}

// check if key exists

hasKey = 'name' in person;

if(hasKey) {

console.log('The key exists.');

}

else{

console.log('The key does not exist.');

}

Output:

The key exists.

Example: 2

index.js

// program to check if a key exists

person = {

id: 1,

name: 'Kishan',

age: 25

}

//check if key exists

hasKey = person.hasOwnProperty('name');

if(hasKey) {

console.log('The key exists.');

}

else {

console.log('The key does not exist.');

}

Output:

The key exists.

I hope it can help you...

#Node JS