簡體   English   中英

將計數值添加到具有相同鍵值的對象(對象數組的數組)

[英]Add count value to object with same key values (array of array of objects)

您好,我要對一組對象進行復雜的迭代。 我在 Javascript 中有這樣的數組:

arr = [
 [{ apiName: 'app/abc', error: '', res: 'response' }],
 [{ apiName: 'app/abc', error: '', res: 'response' }],
 [{ apiName: 'app/abc', error: '', res: 'response' }],
 [{ apiName: 'app/abc', error: 'error's', res: 'response' }],
 [{apiName: 'app/abc', error: 'no error's', res: 'response' }],
 [{apiName: 'app/abc', error: 'no error's', res: 'response' }],
 [{ apiName: 'app/abc', error: '', res: 'response' }],
]

我想為每個對象添加 count 屬性,以計算具有相同名稱和姓氏的對象......所以現在應該是:

[
 { apiName: 'app/abc', error: '', count: 4 },
 { apiName: 'app/abc', error: 'Sheth', count: 2 },
 { apiName: 'app/abc', error: 'Sen', count: 1' },
]

這是我的代碼:

// It works only for array of objects
let summary;
for(i=0; i<arr.length; i++){
 summary = Object.values(arr[i].reduce((a,{apiName, error}) => {
  let k = `${apiName}_${error}`;
  a.push(a[k] = a[k] || {apiName, error, count : 0});
  a[k].count++;
  return a;
 },[]));
}

您需要減少嵌套數據結構並省略推送到公共鍵。 而是使用帶有鍵和計數的對象。

 const data = [[{ apiName: 'app/abc', error: '', res: 'response' }], [{ apiName: 'app/abc', error: '', res: 'response' }], [{ apiName: 'app/abc', error: '', res: 'response' }], [{ apiName: 'app/abc', error: 'error', res: 'response ' }], [{ apiName: 'app/abc', error: 'no error', res: 'response' }], [{ apiName: 'app/abc', error: 'no error', res: 'response ' }], [{ apiName: 'app/abc', error: '', res: 'response' }]], summary = Object.values(data.reduce((r, array) => array.reduce((a, { apiName, error }) => { const key = `${apiName}_${error}`; a[key]??= { apiName, error, count: 0 }; // or a[key] = a[key] || { apiName, error, count: 0 }; a[key].count++; return a; }, r), [])); console.log(summary);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

暫無
暫無

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

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