Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all elements of an object that has no value, empty or null

Tags:

javascript

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.

like image 402
justin hernandez Avatar asked Dec 03 '22 20:12

justin hernandez


1 Answers

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.

like image 70
Hussain Ali Akbar Avatar answered Dec 06 '22 12:12

Hussain Ali Akbar