我认为我的问题很简单,我似乎无法弄清楚。我需要从一组对象中取出:
let testArrays = [
{ "containerType": "2 Gallon", "wasteType": "10000001", "vol": "2 Gallons" },
{ "containerType": "2 Gallon", "wasteType": "10000001", "vol": "2 Gallons" },
{ "containerType": "2 Gallon", "wasteType": "10000002", "vol": "2 Gallons" },
{ "containerType": "2 Gallon", "wasteType": "10000002", "vol": "2 Gallons" },
{ "containerType": "2 Gallon", "wasteType": "10000003", "vol": "2 Gallons" },
{ "containerType": "5 Gallon", "wasteType": "10000003", "vol": "5 Gallons" },
{ "containerType": "5 Gallon", "wasteType": "10000003", "vol": "5 Gallons" },
{ "containerType": "5 Gallon", "wasteType": "10000003", "vol": "5 Gallons" },
{ "containerType": "5 Gallon", "wasteType": "10000004", "vol": "5 Gallons" }
]
对于内部带有数组的分组对象,按上面的“wasteType”分组并带有计数。体积将通过将计数乘以“vol”中的值来创建,我可以使用 parsefloat 我相信:
let wastes = {
"10000001": [
{
"containerType": "2 Gallon",
"count": 2,
"vol": "4 Gallons"
}
],
"10000002": [
{
"containerType": "2 Gallon",
"count": 2,
"vol": "4 Gallons"
}
],
"10000003": [
{
"containerType": "1 Gallon",
"count": 1,
"vol": "2 Gallons"
},
{
"containerType": "5 Gallon",
"count": 3,
"vol": "15 Gallons"
}
],
"10000004": [
{
"containerType": "5 Gallon",
"count": 1,
"vol": "5 Gallons"
}
],
}
我知道我应该为此使用 array.map() 但我不知道该怎么做。我到处都在寻找这个特定的例子,但找不到。非常感谢所有帮助。
你需要使用reduce
而不是map
wasteType
作为属性名称final
再次循环以获得 vol,即count * vol
let testArrays = [{"containerType": "2 Gallon","wasteType": "10000001","vol": "2 Gallons"}, {"containerType": "2 Gallon","wasteType": "10000001","vol": "2 Gallons"}, {"containerType": "2 Gallon","wasteType": "10000002","vol": "2 Gallons"}, {"containerType": "2 Gallon","wasteType": "10000002","vol": "2 Gallons"}, {"containerType": "2 Gallon","wasteType": "10000003","vol": "2 Gallons"}, {"containerType": "5 Gallon","wasteType": "10000003","vol": "5 Gallons"}, { "containerType": "5 Gallon","wasteType": "10000003","vol": "5 Gallons"}, {"containerType": "5 Gallon","wasteType": "10000003","vol": "5 Gallons"}, {"containerType": "5 Gallon","wasteType": "10000004","vol": "5 Gallons"}]
let final = testArrays.reduce((op, { containerType, wasteType,vol}) => {
let obj = { containerType, vol, count: 0 }
op[wasteType] = op[wasteType] || new Map([[containerType,obj]])
if(op[wasteType].has(containerType)){
op[wasteType].get(containerType).count++
} else{
obj.count++
op[wasteType].set(containerType, obj)
}
return op
}, {})
for(let key in final){
final[key] = [...final[key].values()].map(value=>{
let { containerType, vol, count} = value
let finalVol = (vol.replace(/[.\D+]/g, '') * count) + " Gallons"
return { containerType, vol:finalVol, count }
})
}
console.log(final)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句