我有一个js对象数组,如下所示:
var person = [{
firstName: "",
lastName: "Doe",
age: 46
}, {
firstName: "John",
lastName: "",
age: 35
}];
如何确定数组中的至少一些对象(例如firstName:
或lastName:
)是否为空?被调用函数的结果只需要是true
或false
。
答案 0 :(得分:1)
你可以使用过滤器和放大器长度如:
const isEmpty = person.filter(x => !x.firstName || !x.lastName).length > 0
或者,使用some
之类的:
const isEmpty = person.some(x => !x.firstName || !x.lastName);
修改: - 强>
function filterItems(TableData) {
return TableData.filter(function(el) {
return Object.values(el).some(v => !v);
})
}
答案 1 :(得分:1)
您可以使用forEach
迭代数组并使用Object.values
获取所有值。然后使用indexOf
测试值是否匹配。使用变量保存状态
var person = [{
firstName: "",
lastName: "Doe",
age: 46
},
{
firstName: "John",
lastName: "",
age: 35
}
];
function testArray(arr) {
var isEmpty = false
arr.forEach(function(item) {
if (Object.values(item).indexOf("") !== -1) {
isEmpty = true
}
})
return isEmpty;
}
console.log(testArray(person))

答案 2 :(得分:1)
如果至少有一个项为null或为空,则返回false
const person = [{
firstName: "",
lastName: "Doe",
age: 46
}, {
firstName: "John",
lastName: "",
age: 35
}];
const allItemsHaveValue = person.map(o => Object.values(o).every(v => v)).every(v => v);
console.log('All items have value: ', allItemsHaveValue);