How to get key name when the value contains empty in an object with JavaScript?


Let’s say the following is our object −

var details = {
   firstName: 'John',
   lastName: '',
   countryName: 'US'
}

Use Object.keys() along with find() to get the key name with empty value. Following is the code −

Example

var details = {
   firstName: 'John',
   lastName: '',
   countryName: 'US'
}
var result = Object.keys(details).find(key=> (details[key] === '' ||
details[key] === null));
console.log("The key is="+result);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo118.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo118.js
The key is=lastName

Updated on: 09-Sep-2020

650 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements