JS:商品多规格笛卡尔积

this.sku = [{
    
    
	name: '颜色',
		value: ['蓝色', '白色', '紫色']
	}, {
    
    
		name: '尺码',
		value: ['S', 'M']
	}, {
    
    
		name: '款式',
		value: ['成人', '小孩']
	}
]

combineSpecs(specs) {
    
    
	if (specs.length === 0) {
    
    
		return [
			[]
		];
	} else {
    
    
		const [head, ...tail] = specs;
		const rest = this.combineSpecs(tail);
		const pairs = head.value.map(value => rest.map(r => [value, ...r]));
		return [].concat(...pairs);
	}
}

// 使用
let arr = this.combineSpecs(this.sku);
console.log(arr)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40745143/article/details/131140327