简体   繁体   English

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

[英]Check if properties in TypeScript Object are empty

I have an object that looks like this:我有一个看起来像这样的对象:

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

I want to check if the properties of products are null (simply Array(0) ).我想检查产品的属性是否为null (只是Array(0) )。 How can I do it?我该怎么做?

I am using "target": "es2015".我正在使用“目标”:“es2015”。

You could probably use lodash _.isEmpty(value) :您可能可以使用lodash _.isEmpty(value)

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

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

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

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

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

Could try this:可以试试这个:

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
}

This is not a catch all solution, it needs more work for use beyond your stated case.这不是一个包罗万象的解决方案,它需要更多的工作才能在您陈述的情况之外使用。 Specifically, it only works on objects of one level deep.具体来说,它只适用于一层深度的对象。 If you are passing in a nested object, you'll have to adjust the function to be recursive.如果传入嵌套对象,则必须将函数调整为递归。 If you expect to have other data types, you will have to do some handling of those inside the filter function (the .length call will fail on numbers and objects, among others).如果您希望有其他数据类型,则必须对过滤器函数内部的那些数据类型进行一些处理(.length 调用将在数字和对象等上失败)。

After more thought, I like this solution more.经过更多思考,我更喜欢这个解决方案。

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

For checking if all the arrays are empty, you can approach it as follow:要检查所有数组是否为空,您可以按如下方式进行处理:

This is assuming that all values are arrays这是假设所有值都是数组

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

As the argument is an array, we can use the destructuring assignment as follow:由于参数是一个数组,我们可以使用如下解构赋值:

{length} // Basically to extract the attribute length

The number 0 is considered falsy , so we can do explicit type coercion (or type casting) on values as follow:数字 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