【发布时间】:2021-11-19 19:35:04
【问题描述】:
我有一个这样的数组:
var objects = [{
cat: "Fixtures"
name: "brilliance_denali_(best)"
shadowColor: "warmWhite"
subCat: "Spot & Bullet Lights"
title: "Brilliance Denali (Best)"
wattage: {upPrice: 10, value: '10W'}
},
{
cat: "Fixtures"
name: "brilliance_denali_(best)"
shadowColor: "warmWhite"
subCat: "Spot & Bullet Lights"
title: "Brilliance Denali (Best)"
wattage: {upPrice: 10, value: '10W'}
},
{
cat: "Fixtures"
name: "brilliance_denali_(best)"
shadowColor: "red"
subCat: "Spot & Bullet Lights"
title: "Brilliance Denali (Best)"
wattage: {upPrice: 12, value: '12W'}
},
{
cat: "Fixtures"
name: "bullet_lights"
shadowColor: "blue"
subCat: "Lights"
title: "Bullet Lights"
wattage: {upPrice: 28, value: '10W'}
}]
我想根据“cat”减少这个数组,然后在 cat 内部是“subCat”,然后在我想用额外的“COUNT”键减少它们的对象内部,如果它们具有相同的“名称”,“ shadowColor”和“功率值”。所以总的输出数组应该是这样的:
var formattedObjects = [
{
cat: 'Fixtures',
children: [
{
subCat: 'Lights',
childres: [
{
cat: "Fixtures"
name: "bullet_lights"
shadowColor: "blue"
subCat: "Lights"
title: "Bullet Lights"
wattage: {upPrice: 28, value: '10W'},
count: 1 <-- COUNT BASED ON SAME : NAME && SHADOWCOLOR && WATTAGE VALUE
}
]
}, {
subCat: 'Spot & Bullet Lights',
childres: [
{
{
cat: "Fixtures"
name: "brilliance_denali_(best)"
shadowColor: "warmWhite"
subCat: "Spot & Bullet Lights"
title: "Brilliance Denali (Best)"
wattage: {upPrice: 10, value: '10W'},
count: 2 <-- COUNT BASED ON SAME : NAME && SHADOWCOLOR && WATTAGE VALUE
},
{
cat: "Fixtures"
name: "brilliance_denali_(best)"
shadowColor: "red"
subCat: "Spot & Bullet Lights"
title: "Brilliance Denali (Best)"
wattage: {upPrice: 12, value: '12W'},
count: 1 <-- COUNT BASED ON SAME : NAME && SHADOWCOLOR && WATTAGE VALUE
}
}
]
}
]
}
]
到目前为止,我能够根据“subCat”和“cat”来减少它,每个都有嵌套的孩子,但我不确定我应该如何在其中添加计数并删除具有相同“名称”、“sahdowColor”的对象和“瓦数”。这就是我的减速器在不计数时的样子:
const formatedObjects = objects.reduce((list, item) => {
const { cat, subCat } = item;
const hasList = !!list?.[cat];
const subList = list?.[cat]?.children.find(child => child.subCat === subCat)
const value = {
name: item.name,
title: item.title,
shadowColor: item.shadowColor ? item.shadowColor : null ,
wattage: item.wattage ? item.wattage : null
}; // the element in data property
if (!hasList) {
list[cat] = { cat, children: [
{
subCat,
children: [value]
}
]}
} else if (!subList){
list[cat].children.push({ subCat, children: [value]})
} else {
subList.children.push(value)
}
return list;
}, {})
知道我应该如何在减速器中添加计数吗???谢谢。
【问题讨论】:
标签: javascript arrays reduce