【问题标题】:Check if there are null values in an array of objects检查对象数组中是否有空值
【发布时间】:2016-06-24 17:41:22
【问题描述】:

我有这个对象数组。

[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'

如您所见,Object[0] 的 Date 和 Location 有空值。我想检查整个对象数组中是否存在空值。 如果“日期”和“位置”存在空值,我应该能够在控制台上显示“空值存在”。如果不存在空值,它应该在控制台上显示“数据正确”。

有人可以告诉我如何实现这一点。

【问题讨论】:

  • 是字符串类型的'null' 还是null?当存在空值但不是“日期”或“位置”时,您想返回什么?
  • null 是如何从 null 变为字符串的?当我第一次看到这个问题时,忍者不是被编辑了吗?

标签: javascript arrays object iteration underscore.js


【解决方案1】:
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');

【讨论】:

  • 感谢最简单的答案和我一直在寻找的答案
【解决方案2】:

使用 Object.keys()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);
});

【讨论】:

  • Array.prototype.some() 出现是合乎逻辑的,但我相信 findIndex 会以某种方式更快。
【解决方案3】:

使用 some() 并检查是否有 null。

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

【讨论】:

    【解决方案4】:

    使用下划线的解决方案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-01
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多