繁体   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