Reputation: 1033
Lets say I have array like this :
[
{
"id" : "1"
"name": "David",
"age": "20"
},
{
"id" : "2"
"name": "",
"age": "18"
},
{
"id" : "3"
"name": "Micheal",
"age": "25"
},
{
"id" : "4"
"name": "Wonder Women",
"age": "20"
},
{
"id" : "5"
"name": "Clark",
"age": ""
}
]
Some of the contents are empty. How to write the condition if "age" is null and "name" is null.
Upvotes: 0
Views: 60
Reputation: 115
As your request is not definitive, I'm assuming you want the person elements that satisfy your criteria in a new array, called personsWithoutNameAndAge.
You can achieve this very elegantly, using functional programming:
const personsWithoutNameAndAge = persons.filter(person => !person.name && !person.age)
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The function we provide the filter function (the argument passed to it) only passes the test (returns true) if both person.name and person.age are falsy. Empty string, undefined, and null are all falsy and so the function will successfully work with any of these values representing 'null'.
Hope this helps!
Upvotes: 1
Reputation: 676
You can filter the array and then use it where you need:
const myFilteredArray = arr.filter(item => {
return item.name !== null && item.age !== null
})
// use myFilteredArray in your code.
Upvotes: 1