美文网首页
使用递归处理商品SKU数据

使用递归处理商品SKU数据

作者: Yinzhishan | 来源:发表于2022-08-04 11:11 被阅读0次

原因

最近在写一个商城的后台,一个商品的属性是可以无限添加的,通过商品属性可以组合出所有的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)





相关文章

网友评论

      本文标题:使用递归处理商品SKU数据

      本文链接:https://www.haomeiwen.com/subject/pkxairtx.html