Home > Mobile >  how to group objects which have same value and include the values that differ with javascript/typesc
how to group objects which have same value and include the values that differ with javascript/typesc

Time:08-11

I get following response :

{ "Dispositif": [ { "libele": "AAA", "Fonds": "xxx", "Estimation": "122", "Parts": "11" }, { "libele": "AAA", "Fonds": "yyy", "Estimation": "111", "Parts": "12", }, { "libele": "BBB", "Fonds": "zzz", "Estimation": "111", "Parts": "12", }, { "libele": "BBB", "Fonds": "aaa", "Estimation": "111", "Parts": "12", }, { "libele": "CCC", "Fonds": "aaa", "Estimation": "111", "Parts": "12", }, ] }

What I would like to get :

{ "Dispositif" : [ { "libele": "A"; "data": [ {"Fonds": "xxx","Estimation": "122","Parts": "11"},{"Fonds": "yyy","Estimation": "111","Parts": "12",}b] }, { "libele": "B"; "data": [ {"Fonds": "zzz","Estimation": "111","Parts": "12"},{"Fonds": "ccc","Estimation": "111","Parts": "12",}b] }, { "libele": "C"; "data": [ {"Fonds": "ddd","Estimation": "111","Parts": "12"}] } ] }

CodePudding user response:

You should use reduce operator to group items, below you will find the complete solution:

const data = [
  {
    libele: 'AAA',
    Fonds: 'xxx',
    Estimation: '122',
    Parts: '11',
  },
  {
    libele: 'AAA',
    Fonds: 'yyy',
    Estimation: '111',
    Parts: '12',
  },
  {
    libele: 'BBB',
    Fonds: 'zzz',
    Estimation: '111',
    Parts: '12',
  },
  {
    libele: 'BBB',
    Fonds: 'aaa',
    Estimation: '111',
    Parts: '12',
  },
  {
    libele: 'CCC',
    Fonds: 'aaa',
    Estimation: '111',
    Parts: '12',
  },
];

const grouped = data.reduce((total, item) => {
  const existingGroup = total.find((group) => group.libele === item.libele);

  if (existingGroup) {
    existingGroup.data.push(item);
  } else {
    total.push({
      libele: item.libele,
      data: [item],
    });
  }

  return total;
}, []);

console.log(grouped);

  • Related