检查对象数组中是否有空值

Check if there are null values in an array of objects

我有这个对象数组。

[Object, Object, Object]
0:Object
 name: "Rick"
 Contact: "Yes"
 Date:'null'
 Location:'null'
1:Object
 name:"Anjie"
 Contact:"No"
 Date:'13/6/2016'
 Location:'LA'
2:Object
 name:"dillan"
 Contact:"Maybe"
 Date:'17/6/2016'
 Location:'NY'

如您所见,日期和位置的对象[0] 为空值。我想检查整个对象数组中是否存在空值。 如果 'Date' 和 'Location' 存在空值,我应该能够在控制台上显示 'Null present'。如果不存在空值,它应该在控制台上显示 'Data right'。

谁能告诉我如何实现这一目标。

var wasNull = false;
for(var i in objectsArray) {
  if(objectsArray[i].Date == null || objectsArray[i].Location == null) wasNull = true;
}
if(wasNull) console.log('Was null');
else console.log('Data right');

使用Object.keys() and Array#some方法

var data = [{
  name: "Rick",
  Contact: "Yes",
  Date: null,
  Location: null
}, {
  name: "Anjie",
  Contact: "No",
  Date: '13/6/2016',
  Location: 'LA'
}, {
  name: "dillan",
  Contact: "Maybe",
  Date: '17/6/2016',
  Location: 'NY'
}];


// iterate over array elements
data.forEach(function(v, i) {
  if (
    // get all properties and check any of it's value is null
    Object.keys(v).some(function(k) {
      return v[k] == null;
    })
  )
    console.log('null value present', i);
  else
    console.log('data right', i);
});

使用 some() 并检查是否存在空值。

var arr = [
   { a : "a", b : "b", c : "c" },
   { a : "a", b : "b", c : "c" },
   { a : "a", b : "b", c : null }
];

function hasNull(element, index, array) {
  return element.a===null || element.b===null || element.c===null;
}
console.log( arr.some(hasNull) );

如果您不想对 if 进行硬编码,那么您需要添加另一个循环并遍历键。

var arr = [
   { a : "a1", b : "b1", c : "c1" },
   { a : "a2", b : "b2", c : "c2" },
   { a : "a3", b : "b3", c : null }
];

function hasNull(element, index, array) {
  return Object.keys(element).some( 
    function (key) { 
      return element[key]===null; 
    }
  ); 
}
console.log( arr.some(hasNull) );

或 JSON 带有正则表达式 (

var arr = [
   { a : "a1", b : "b1", c : "c1" },
   { a : "a2", b : "b2", c : "c2" },
   { a : "a3", b : "b3", c : null }
];

var hasMatch = JSON.stringify(arr).match(/:null[\},]/)!==null;
console.log(hasMatch);

使用下划线的解决方案:

var nullPresent = _.some(data, item => _.some(_.pick(item, 'Date', 'Location'), _.isNull));