如何在js中验证对象数组为空/空/未定义

时间:2017-12-31 05:03:12

标签: javascript arrays object

我有一个js对象数组,如下所示:

var person = [{
  firstName: "",
  lastName: "Doe",
  age: 46
}, {
  firstName: "John",
  lastName: "",
  age: 35
}];  

如何确定数组中的至少一些对象(例如firstName:lastName:)是否为空?被调用函数的结果只需要是truefalse

3 个答案:

答案 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);