簡體   English   中英

計算數組中對象中兩個鍵的出現次數

[英]count occurrences of two keys in objects in array

我有以下數組與對象,並使用以下代碼創建一個鍵“id”的計數器:

 var arr=[ { id: 123, title: "name1", status: "FAILED" }, { id: 123, title: "name1", status: "PASSED" }, { id: 123, title: "name1", status: "PASSED" }, { id: 123, title: "name1", status: "PASSED" }, { id: 1234, title: "name2", status: "FAILED" }, { id: 1234, title: "name2", status: "PASSED" } ]; const test =arr.reduce((tally, item) => { if (!tally[item.id]) { tally[item.id] = 1; } else { tally[item.id] = tally[item.id] + 1; } return tally; }, {}); console.log(test); 

現在我想要做的是修改計數以考慮關鍵狀態,所以結果將是這樣的:

[
{id:123, status:"PASSED", tally:3},
{id:123, status:"FAILED", tally:1},
{id:1234, status:"PASSED", tally:1},
{id:1234, status:"FAILED", tally:1}
]

任何的想法? 謝謝!

只需創建關鍵item.id + item.status ,然后這是一個簡單的任務

 const res = Object.values(arr.reduce((a, b) => { a[b.id + b.status] = Object.assign(b, {tally: (a[b.id + b.status] || {tally: 0}).tally + 1}); return a; }, {})); console.log(res); 
 <script> const arr=[ { id: 123, title: "name1", status: "FAILED" }, { id: 123, title: "name1", status: "PASSED" }, { id: 123, title: "name1", status: "PASSED" }, { id: 123, title: "name1", status: "PASSED" }, { id: 1234, title: "name2", status: "FAILED" }, { id: 1234, title: "name2", status: "PASSED" } ]; </script> 

干得好

const test = arr.reduce((acc, item) => {        
    let found = acc.find(obj => obj.id === item.id && obj.status === item.status)
    if (typeof found === "undefined") {
        item.tally = 1
        acc.push(item);
    } else {
        found.tally++;
    }
    return acc;
}, []);

您應該首先使用包含ID和狀態的密鑰對項目進行分組:

const result = arr.reduce((acc, item) => {
  const key = item.id + item.status;
  acc[key] = acc[key] || { ...item, tally: 0 };
  acc[key].tally++;
  return acc;
}, {});

console.log( Object.values(result) );

輸出:

[
  { id: 123, title: 'name1', status: 'FAILED', tally: 1 },
  { id: 123, title: 'name1', status: 'PASSED', tally: 3 },
  { id: 1234, title: 'name2', status: 'FAILED', tally: 1 },
  { id: 1234, title: 'name2', status: 'PASSED', tally: 1 },
]

只需創建一個結合了idstatus的密鑰。 並使用它制作地圖。 之后,您可以從中獲得所需的結果。 請嘗試以下方法:

 var arr=[{id:123,title:"name1",status:"FAILED"},{id:123,title:"name1",status:"PASSED"},{id:123,title:"name1",status:"PASSED"},{id:123,title:"name1",status:"PASSED"},{id:1234,title:"name2",status:"FAILED"},{id:1234,title:"name2",status:"PASSED"}]; const map =arr.reduce((tally, item) => { tally[item.id+"_"+item.status] = (tally[item.id+"_"+item.status] || 0) +1; return tally; }, {}); const result = Object.keys(map).map((a)=>{ var obj = { id : a.split("_")[0], status : a.split("_")[1], tally : map[a] }; return obj; }); console.log(result); 

暫無
暫無

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

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