Home » How to find keys of an object using javascript

How to find keys of an object using javascript

Javascript comes with built in features and methods that can be useful for solving complex problems.

In order to find a key of an Object in Javascript we can use following ES6 functions

The question of the day is we want to find the List of fields defined as keys in the following snippet of code.


const parkingLot = {
  id: 1,
  parkingLotName: 'A1',
  costPerHours: 10,
  reserved : true,
  date: '27/12/2012' 
}

The keys for parkingLot objects are :

  1. id
  2. parkingLotName
  3. costPerHours
  4. reserved
  5. date

The approach to the finding the list of allKeys would be

  1. Call the Object.keys() method to get an array of the object’s keys.
  2. Using the Object.hasOwnProperty () method to search for an individual key.

1.Using Object.keys() approach to find list of keys in parkingLot object



const parkingLot = {
  id: 1,
  parkingLotName: "A1",
  costPerHours: 10,
  reserved: true,
  date: "27/12/2012"
};

const Key = "parkingLotName";

const listOfAllKeys = 
Object.keys(parkingLot);
// this will return ['id', 
//'parkingLotName', 'costPerHours', 
//'reserved', 'date']

const findKeyInArray = 
listOfAllKeys.filter((currentKey) 
=> currentKey === Key);

console.log({ findKeyInArray });



When you run the code the compiler will give the following output

2. Using the Object.hasOwnProperty () method to search for an individual key.

javascript has also another Object.hasOwnProperty() method that we can use to search for an object key of an object


const parkingLot = {
  id: 1,
  parkingLotName: "A1",
  costPerHours: 10,
  reserved: true,
  date: "27/12/2012"
};

const key = "parkingLotName";

const checkIfObjectHasId 
= parkingLot.hasOwnProperty(key);
// this will return boolean

if (checkIfObjectHasId) {
  console.log(
  { valueOfElement: parkingLot[key] }
  );
  // this will return 'A1'
}


Learn Javascript using javascript book found on Amazon kindle

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Best Coding Ideas in JavaScript

How event loops works in Javascript?

Mastering Loops in JavaScript: A Comprehensive Guide

How to authenticate pages in Vuejs (OIDC)

How Fetch works in JavaScript?

Sorting arrays in Javascript using array.sort()

Chat Icon