Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get key name when the value contains empty in an object with JavaScript?
To find keys with empty values in a JavaScript object, you can use Object.keys() combined with find() or filter(). This is useful for form validation or data cleaning.
Let's say we have the following object:
var details = {
firstName: 'John',
lastName: '',
countryName: 'US'
};
Using Object.keys() with find()
To find the first key with an empty value, use Object.keys() along with find():
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);
The key is=lastName
Using Object.keys() with filter() for Multiple Keys
To find all keys with empty values, use filter() instead:
var details = {
firstName: 'John',
lastName: '',
email: null,
countryName: 'US',
city: ''
};
var emptyKeys = Object.keys(details).filter(key => (details[key] === '' || details[key] === null));
console.log("Keys with empty values:", emptyKeys);
Keys with empty values: [ 'lastName', 'email', 'city' ]
Handling Different Empty Types
You can check for various empty conditions like undefined, null, and empty strings:
var details = {
firstName: 'John',
lastName: '',
email: null,
age: undefined,
countryName: 'US'
};
var emptyKeys = Object.keys(details).filter(key => {
return details[key] === '' || details[key] === null || details[key] === undefined;
});
console.log("All empty keys:", emptyKeys);
All empty keys: [ 'lastName', 'email', 'age' ]
Conclusion
Use Object.keys() with find() to get the first empty key, or with filter() to get all empty keys. This approach handles null, undefined, and empty string values effectively.
Advertisements
