【问题标题】:How to check if objects in an array is null. i.e. the key value pair is null如何检查数组中的对象是否为空。即键值对为空
【发布时间】:2020-05-08 07:18:41
【问题描述】:

这是由空对象组成的对象数组:

arr = [{
  yieldConventionId: null,
  yieldConventionName: null,
  yieldCurveSectorId: null,
  yieldCurveSectorName: null,
  yieldCurveTypeId: null,
  yieldCurveTypeName: null,
}]

如何为此类对象编写空检查条件。

【问题讨论】:

  • 所以你想要一个函数来告诉你这个对象是空的,以防它的所有属性都是空的?
  • 所有字段是否为空,我想检查一下。这样我就可以在此基础上应用一些其他条件。任何解决方法都可以。

标签: arrays json angular object


【解决方案1】:

您可以检查任何值是否不为 Null,这里是返回一个具有 true、false、true 的数组,其中至少有一个不为 null。我用过Array.map()Array.some()

const arr= [{
    'yieldConventionId': null,
    'yieldConventionName': null,
    'yieldCurveSectorId': null,
    'yieldCurveSectorName': null,
    'yieldCurveTypeId': null,
    'yieldCurveTypeName': null
   },
   {'yieldConventionId': null,
    'yieldConventionName': null,
    'yieldCurveSectorId': 'some value',
    'yieldCurveSectorName': null,
    'yieldCurveTypeId': null,
    'yieldCurveTypeName': null
   }
   ];
   
const isAllNotNull = arr.map(function(ob) {
  return Object.keys(ob).some(function(k){
    return ob[k] !== null
   });
});

console.log(isAllNotNull)

【讨论】:

  • 谢谢,不幸的是,Object.values 不支持 es5。有什么选择吗?
【解决方案2】:

你可以像这样进行空检查

let isNull=arr.some(item=> (item.yieldConventionId === null || item.yieldConventionName === null || item.yieldCurveSectorId === null|| item.yieldCurveSectorName === null || item.yieldCurveTypeId === null || item.yieldCurveTypeName === null));

如果您的任何值为空,这会将您的 isNull 设置为 true。如果要检查所有值是否为空,可以将|| 更改为&&

【讨论】:

    【解决方案3】:

    由于您使用的是 ES5,因此这里有一个使用多个 for 循环的显式版本。它使用数组every() 方法来检查数组的所有元素(在我们的例子中是对象值)是否都是null

    arr = [
      {
        yieldConventionId: null,
        yieldConventionName: null,
        yieldCurveSectorId: null,
        yieldCurveSectorName: null,
        yieldCurveTypeId: null,
        yieldCurveTypeName: null
      },
      {
        yieldConventionId: null,
        yieldConventionName: null,
        yieldCurveSectorId: null,
        yieldCurveSectorName: 'not null',
        yieldCurveTypeId: null,
        yieldCurveTypeName: null
      },
    ];
    
    const allNull = array => {
      let result = [];
      for (const elem of array) {
        elemArr = [];
        for (const item in elem) {
          if(elem.hasOwnProperty(item)) {
            elemArr.push(elem[item]);
          }
        }
        result.push(elemArr.every(item => item === null));
      }
      return result;
    }
    
    console.log(allNull(arr));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      相关资源
      最近更新 更多