簡體   English   中英

如何計算表中的對象數量

[英]How to count the number of objects in the table

如何獲取表中對象的數量。 我希望所有對象看起來都一樣。 例如,在元素“b”中,我沒有任何對象,但在 output 中,我想獲取計數為 0 的所有已使用對象。

INPUT DATA
{
  a: {
    obj3: [{...}, {...}]
  },
  b: { },
  c: {
    obj1: [{...}, {...}, {...}]
    obj2: [{...}, {...}]
  }
}

OUTPUT DATA

{
  a: {
    obj1: 0,
    obj2: 0,
    obj3: 2
  },
  b: {
    obj1: 0,
    obj2: 0,
    obj3: 0
  },
  c: {
    obj1: 3
    obj2: 2,
    obj3: 0
  }
}

僅當您希望特定數量的objX為 output 並且密鑰名稱的格式相同時,您才能執行此類操作。

 let input = { a: { obj3: [{x:1}, {x:2}] }, b: { }, c: { obj1: [{x:1}, {x:2}, {x:3}], obj2: [{x:1}, {x:2}] } } let output = {}; for (const [key, value] of Object.entries(input)) { let result = {} for (let i = 1; i < 4; i++) { result['obj'+i] = value['obj'+i]? value['obj'+i].length: 0; } output[key] = result; } console.log(output);

為了使代碼保持通用並更易於管理和理解,我將循環遍歷您的數據兩次:首先發現您需要處理的所有唯一鍵,然后用正確的數據填充結構。

獲取正確的密鑰

為了獲得正確的鍵,我查看了輸入 object 的值(我們可以忽略abc鍵)。

我們對這一層中對象的所有鍵感興趣。 我們可以使用flatMap(Object.keys)創建它們的平面列表。

因為這個列表可能包含重復的鍵,所以我將它們存儲在Set中。 這確保所有鍵只出現一次。 使用您提供的示例數據,我們現在有一Set "obj1", "obj2", "obj3"

轉換 object

我們現在可以將任何 object 轉換為具有所有鍵的 object。 我在Result構造函數 function 中捕獲了這種轉換。

這個 function 創建了一個所有鍵的列表( [...allKeys] ), map s 在它們之上,並檢查我們的輸入 object 是否存在鍵(obj[k]? 如果密鑰存在,我們使用它的長度。 如果沒有,我們默認為0

轉換整個輸入

為了轉換你的整個 object,我定義了一個mapObj助手。 這需要一個 object,將 function 應用於其每個值,並使用相同的鍵返回新的 object 中的值。

 const input = { a: { obj3: [{}, {}] }, b: { }, c: { obj1: [{}, {}, {}], obj2: [{}, {}] } }; // Set(3) {"obj1", "obj2", "obj3"} const allKeys = new Set( Object.values(input).flatMap(Object.keys) ); const Result = obj => Object.fromEntries( [...allKeys].map( (k) => [ k, obj[k]?.length || 0 ] ) ); console.log( mapObj(Result, input) ) // Utils function mapObj(f, o) { return Object.fromEntries( Object.entries(o).map( ([k, v]) => [k, f(v)] ) ) }

這是我的解決方案:

 let input = { a: { obj3: [{x:1}, {x:2}] }, b: {}, c: { obj1: [{x:3}, {x:5}, {x:6}], obj2: [{x:7}, {x:8}] } } let output={}; Object.keys(input).forEach(key=>{ let item={obj1:0,obj2:0,obj3:0}; ["obj1","obj2","obj3"].forEach(itemType=>{ if (input[key][itemType]){ item[itemType]= input[key][itemType].length; } }) output[key]=item; }); console.log(output);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM