我得到以下答复:
{ "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", }, ] }我想要的是:
{ "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"}] } ] }发布于 2022-08-09 11:36:26
您应该使用reduce运算符对项进行分组,下面将找到完整的解决方案:
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);
https://stackoverflow.com/questions/73290913
复制相似问题