我有一个具有重复类别的数组,例如
array = {类别:“基于广告的获利”,子类别:“内容和信息服务”},{类别:“资产负债表业务”,子类别:“ test1”},{类别:“资产负债表业务”,子类别:“ test2“}
我希望能够将该数组的值推入新数组,但采用以下格式:
array2 = {类别:“资产负债表业务”,子类别:[{名称:“ test1”},{名称:“ test2”}]}},{类别:“基于广告的获利”,子类别:[{名称:“内容和信息服务“}]
我认为以下应该足以实现您想要的。
和往常一样,有很多优化的方法可以做到这一点,但这应该足以让您入门,并且您可以自己考虑优化。
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句