Reputation: 77
I want to return all elements in an object that has no value, empty or null.. (i.e)
{
firstname: "John"
middlename: null
lastname: "Mayer"
age: ""
gender: "Male"
}
I want to return the middlename and the age in the oject. Please help me. Thank you.
Upvotes: 4
Views: 2584
Reputation: 2208
for (var property in obj ) {
if (obj.hasOwnProperty(property)) {
if (!obj[property]){
console.log(property); // This is what you're looking for, OR 'obj[property]' if you're after the values
}
}
}
You can then use matching properties to create your own object. Instead of logging it to console, you could use it to meet your requirements.
Upvotes: 4
Reputation: 1655
Lets say that your request object is in a variable called obj. You can then do this:
Object.keys(obj).filter(key => obj[key] === null || obj[key] === undefined || obj[key] === "")
Object.keys will fetch all the keys of the object. You will then run a filter function over the object keys to find the required items.
Right now there are three conditions of null, undefined and empty string. You can add more as per your need.
Upvotes: 4
Reputation: 26844
You can convert the object into array by using Object.keys
, Use filter
to filter the data.
Note: this will include all falsey values. Like 0, undefined etc
let obj = {
firstname: "John",
middlename: null,
lastname: "Mayer",
age: "",
gender: "Male"
};
let result = Object.keys(obj).filter(o => !obj[o]);
console.log(result);
If you only want to include empty string and null, you can:
let obj = {
firstname: "John",
middlename: null,
lastname: "Mayer",
age: "",
gender: "Male"
};
let result = Object.keys(obj).filter(o => obj[o] === '' || obj[o] === null);
console.log(result);
Upvotes: 4
Reputation: 370619
Iterate over the entries and filter those properties whose values are null/undefined/empty string:
const obj = { firstname: "John", middlename: null, lastname: "Mayer", age: "", gender: "Male" };
const emptyishProperties = Object.entries(obj)
.filter(([, val]) => val === null || val === undefined || val === '')
.map(([key]) => key);
console.log(emptyishProperties);
If it's OK to also include those whose values are 0
, you could simplify the filter to
.filter(([, val]) => !val)
Upvotes: 4