我需要编辑一个数组,但是我不知道如何开始。
数组是
var products =
[
"rose-S",
"rose-M",
"rose-L",
"rose-XL",
"rose-XL",
"blue-XS",
"blue-L",
"green-M"
]
结构必须是
{
"rose": {
"S": 1,
"M": 1,
"L": 1,
"XL": 2
},
"blue": {
"XS": 1,
"L": 1
},
"green": {
"M": 1
},
}
我能做什么?
答案 0 :(得分:2)
减少数组,并创建一个对象。拆分项目,然后取出color
和size
。如果color
对象不存在,请创建它。创建size
的子对象(如果不存在),并为当前的颜色和大小组合添加1:
const products = ["rose-S","rose-M","rose-L","rose-XL","rose-XL","blue-XS","blue-L","green-M"]
const result = products.reduce((acc, item) => {
const [color, size] = item.split('-') // split and destructure to get the color & size
if(!acc[color]) acc[color] = {} // init color if it doesn't exist
if(!acc[color][size]) acc[color][size] = 0 // init the size if it doesn't exist
acc[color][size] += 1 // add 1 to current color/size
return acc
}, {})
console.log(result)