Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add array of objects with same keys and multiple values in react.js?

I have an array with many objects in it, all of them has the same keys and I want to merge them based on chapter name while not losing any of the other values

enter image description here

I tried different methods, which are lengthy and has not achieved the solution yet, hoping for a solution, which is optimized if possible

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

So basically for sort your problem of merge and group other data without loosing data of variables you need to try this code :

let array = [
  {chapter: 'Case Studies', id: 1, proficiency: 'Basic', score: '0', count: '2'},
  {chapter: 'Determinants', id: 1, proficiency: 'Basic', score: '0', count: '10'},
  {chapter: 'Relations & Functions', id: 1, proficiency: 'Basic', score: '100.00', count: '13'},
  {chapter: 'Case Studies', id: 2, proficiency: 'Intermediate', score: '0', count: '3'},
  {chapter: 'Determinants', id: 2, proficiency: 'Intermediate', score: '10.53', count: '10'},
  {chapter: 'Relations & Functions', id: 2, proficiency: 'Intermediate', score: '70.00', count: '10'},
  {chapter: 'Case Studies', id: 3, proficiency: 'Advanced', score: '0', count: '1'},
  {chapter: 'Relations & Functions', id: 3, proficiency: 'Advanced', score: '100.00', count: '6'}
];

let result = {};

array.forEach(function(item) {
  if (result[item.chapter]) {
    result[item.chapter].push({
      id: item.id,
      proficiency: item.proficiency,
      score: item.score,
      count: item.count
    });
  } else {
    result[item.chapter] = [{
      id: item.id,
      proficiency: item.proficiency,
      score: item.score,
      count: item.count
    }];
  }
});

let finalResult = [];

for (let key in result) {
  finalResult.push({
    chapter: key,
    values: result[key]
  });
}

console.log(finalResult);

Result look like :

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading