编辑阵列

时间:2020-11-12 19:33:06

标签: javascript arrays

我需要编辑一个数组,但是我不知道如何开始。

数组是

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 
  }, 
}

我能做什么?

1 个答案:

答案 0 :(得分:2)

减少数组,并创建一个对象。拆分项目,然后取出colorsize。如果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)

豫ICP备18024241号-1