简体   繁体   中英

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

Hello I have kind of complicated iteration to be done over an array of array of objects. I have array like this in 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' }],
]

I would like to add count property to each object that counts objects with same name and surname... So it should be now:

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

Here is my code:

// 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;
 },[]));
}

You need to reduce the nested data structure and omit pushing to the common key. Instead use an object with the key and count.

 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM