首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将重复项的所有子类别分组到一个新数组中的一个类别下

如何将重复项的所有子类别分组到一个新数组中的一个类别下
EN

Stack Overflow用户
提问于 2021-01-20 03:06:44
回答 1查看 15关注 0票数 0

例如,我有一个包含重复类别的数组

array ={类别:“基于广告的货币化”,SubCategory:“内容和信息服务”},{类别:“资产负债表业务”,SubCategory:"test1"},{类别:“资产负债表业务”,SubCategory:"test2"}

我希望能够将该数组的值推送到一个新的数组中,但格式如下:

array2 ={类别:“资产负债表业务”,SubCategory:{名称:"test1"},{名称:"test2"}},{类别:“基于广告的货币化”,SubCategory:{名称:“内容和信息服务”}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-20 03:26:40

我认为以下内容应该足以实现你想要的。

像往常一样,有很多优化的方法可以做同样的事情,但这应该足以让你开始,你可以考虑自己的优化。

代码语言:javascript
复制
var array = [{ Category: "Ad-Based Monetization", SubCategory: "Content & Information Services"}, { Category: "Balance sheet businesses", SubCategory: "test1"}, { Category: "Balance sheet businesses", SubCategory: "test2"}]

var obj = {}

// Create a simple lookup with Category as key and SubCategories as value
array.forEach(arr => {
    if(obj.hasOwnProperty(arr.Category)){
        obj[arr.Category].push(arr.SubCategory);
    } else {
        obj[arr.Category] = [arr.SubCategory];
    }
});

const final = []

// Loop over the obj created and format it into the desired structure
for (let Category in obj){
    const SubCategory = obj[Category].map(name => ({name}));
    final.push({Category, SubCategory})
}

console.log(final);

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

https://stackoverflow.com/questions/65797892

复制
相关文章

相似问题

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