假设我有这样的数组:
[
{
"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": ""
}
]
部分内容为空。如果“age”为null且“name”为null,如何编写条件。
答案 0 :(得分:1)
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!
答案 1 :(得分:1)
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.