簡體   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