首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何对具有相同值并包含与javascript/typescript不同的值的对象进行分组(Json/ values )

如何对具有相同值并包含与javascript/typescript不同的值的对象进行分组(Json/ values )
EN

Stack Overflow用户
提问于 2022-08-09 11:15:35
回答 1查看 41关注 0票数 -1

我得到以下答复:

代码语言:javascript
运行
复制
{ "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", }, ] }

我想要的是:

代码语言:javascript
运行
复制
{ "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"}] } ] }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-09 11:36:26

您应该使用reduce运算符对项进行分组,下面将找到完整的解决方案:

代码语言:javascript
运行
复制
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);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73290913

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档