繁体   English   中英

检查 TypeScript 对象中的属性是否为空

[英]Check if properties in TypeScript Object are empty

我有一个看起来像这样的对象:

protected products: {
  color: string[],
  brand: number[],
} = {};

我想检查产品的属性是否为null (只是Array(0) )。 我该怎么做?

我正在使用“目标”:“es2015”。

您可能可以使用lodash _.isEmpty(value)

_.isEmpty(null);
// => true

_.isEmpty(true);
// => true

_.isEmpty(1);
// => true

_.isEmpty([1, 2, 3]);
// => false

_.isEmpty({ 'a': 1 });
// => false

可以试试这个:

const checkEmptyObj = (object) => {
  // gets an array of the values for each kv pair in your object
  const values =  Object.values(object);

  // if you add kv pairs with non array types, will have to adjust this
  // removes all zero length arrays (or strings) from values array
  const nonEmptyValues = values.filter(value => value.length > 0)

  // if any items are in the nonEmptyValues array, return false
  return nonEmptyValues.length < 1
}

这不是一个包罗万象的解决方案,它需要更多的工作才能在您陈述的情况之外使用。 具体来说,它只适用于一层深度的对象。 如果传入嵌套对象,则必须将函数调整为递归。 如果您希望有其他数据类型,则必须对过滤器函数内部的那些数据类型进行一些处理(.length 调用将在数字和对象等上失败)。

经过更多思考,我更喜欢这个解决方案。

return values.every(value => value.length === 0)

要检查所有数组是否为空,您可以按如下方式进行处理:

这是假设所有值都是数组

 let products = {color: [],brand: []}; let allEmpty = Object.values(products).every(({length}) => !Boolean(length)); console.log(allEmpty);

由于参数是一个数组,我们可以使用如下解构赋值:

{length} // Basically to extract the attribute length

数字 0 被认为是falsy ,因此我们可以对值进行显式类型强制(或类型转换),如下所示:

!Boolean(length) // Coerce to boolean the number from arr.length
                 // The negation is needed because if the length === 0 that 
                 // means the array is empty, so we want the result 
                 // as true in our handler for the function every

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM