无意中刷到一位小伙伴的提问,说是将手机型号:荣耀V30、荣耀V30Pro,颜色:蓝色、黑色,容量大小:6+128、8+128、8+256,这些属性实现全组合,也就是生成如下数据结构:手机型号:荣耀V30、颜色:蓝色、容量大小:6+128,手机型号:荣耀V30、颜色:黑色、容量大小:8+128,手机型号:荣耀V30、颜色:黑色、容量大小:8+256……
本着周末在家边带娃边撸代码的一贯风格,写了个demo,具体代码如下:
const productTypeList = [ { attrId:'color', attrInfo:['红色','绿色']
},
{
attrId:'model',
attrInfo:['V30','V30Pro']
},
{
attrId:'memorySize',
attrInfo:['6+128','8+128','8+256']
},
];
const result = [];
function getResult(obj,listIndex,list,id,info){
for (let index = 0; index < list[listIndex][info].length; index++){
obj[list[listIndex][id]]=list[listIndex][info][index]
if(listIndex<list.length-1){
getResult(obj,listIndex+1,list,id,info)
}else{
result.push(JSON.parse(JSON.stringify(obj)))
}
}
}
getResult({},0,productTypeList,'attrId','attrInfo')
console.log(result)复制代码
打印结果如下图所示:
Time!