Reputation: 39
I have list of objects in an array. How can i filter out if any one of key property of the object is null/empty. In given example the first record is perfect and the 2nd and 4th record have missing properties. So my ideal output should be 1st & 2nd.
[{
"ServiceArea": "NON-CIO",
"ManagingDirector": "qwe",
"Lead": "abc",
"Manager": "xyz"
"id":"1",
"Designation":"COO"
},
{
"ServiceArea": "NON-CIO",
"ManagingDirector": "dfg",
"Lead": "",
"Manager": "lkj"
"id":"2",
"Designation":"CTO"
},
{
"ServiceArea": "NON-CIO",
"ManagingDirector": "out",
"Lead": "poi",
"Manager": "",
"id":"43",
"Designation":"COO"
},
{
"ServiceArea": "4500-CIO",
"ManagingDirector": "yhh",
"Lead": "trr",
"Manager": "nbb"
"id":"403",
"Designation":"CTO"
}
]
Upvotes: 1
Views: 51
Reputation: 31987
Use Array.filter
, then use Array.every
to check whether every value is truthy.
const arr=[{ServiceArea:"NON-CIO",ManagingDirector:"qwe",Lead:"abc",Manager:"xyz",id:"1",Designation:"COO"},{ServiceArea:"NON-CIO",ManagingDirector:"dfg",Lead:"",Manager:"lkj",id:"2",Designation:"CTO"},{ServiceArea:"NON-CIO",ManagingDirector:"out",Lead:"poi",Manager:"",id:"43",Designation:"COO"},{ServiceArea:"4500-CIO",ManagingDirector:"yhh",Lead:"trr",Manager:"nbb",id:"403",Designation:"CTO"}];
const res = arr.filter(e => Object.values(e).every(k => !!k))
console.log(res)
If you want to filter by specific keys, you can store the keys in an array and use Array.every
to check if all values are truthy.
const arr=[{ServiceArea:"NON-CIO",ManagingDirector:"qwe",Lead:"abc",Manager:"xyz",id:"1",Designation:"COO"},{ServiceArea:"NON-CIO",ManagingDirector:"dfg",Lead:"",Manager:"lkj",id:"2",Designation:"CTO"},{ServiceArea:"NON-CIO",ManagingDirector:"out",Lead:"poi",Manager:"",id:"43",Designation:"COO"},{ServiceArea:"4500-CIO",ManagingDirector:"yhh",Lead:"trr",Manager:"nbb",id:"403",Designation:"CTO"}];
const keys = ["Lead"]
const res = arr.filter(e => keys.every(k => !!e[k]))
console.log(res)
Upvotes: 2