原因
最近在写一个商城的后台,一个商品的属性是可以无限添加的,通过商品属性可以组合出所有的sku;
例如:
颜色: 1 、2;
内存: 3、4;
固态: 5、6、7;
那么可能有的sku就有3种属性的排列组合共12种;
就要输出在table中输出所有的sku,让运营上传图片等信息;
解决方法
想到用递归解决,这是一个平面的递归,使用最后一个属性作为结束递归的条件;
代码如下:
const data = [
{
"attrKeyId": 1,
"attrKeyName": "",
"isImage": false,
"saleAttrList": [
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "1"
},
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "2"
}
],
"saleKeyId": 1,
"attrKeyAlias": "颜色"
},
{
"attrKeyId": 2,
"attrKeyName": "",
"isImage": false,
"saleAttrList": [
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "3"
},
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "4"
}
],
"saleKeyId": 2,
"attrKeyAlias": "尺码"
},
{
"attrKeyId": '',
"attrKeyName": "",
"isImage": false,
"saleAttrList": [
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "5"
},
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "6"
}
],
"saleKeyId": 2,
"attrKeyAlias": "尺码"
},
{
"attrKeyId": 2,
"attrKeyName": "",
"isImage": false,
"saleAttrList": [
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "7"
},
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "8"
},
{
"attrKeyId": "",
"attrKeyName": "",
"attrValue": "9"
}
],
"saleKeyId": 2,
"attrKeyAlias": "尺码"
}
];
function deepList(nowList, list, i) {
const saleAttrList = list[i].saleAttrList;
if (list[i].attrKeyId == false) {
deepList([...nowList], list, i + 1)
return
}
saleAttrList.map((item) => {
const arr = [...nowList];
arr.push(item.attrValue)
if (i == list.length - 1) {
console.log('arr=>', arr);
} else {
deepList(arr, list, i + 1)
}
})
}
deepList([], data, 0)
网友评论