SKU商品后臺(tái)管理規(guī)格生成

SKU商品后臺(tái)管理規(guī)格生成

關(guān)于:

在做商品管理系統(tǒng)經(jīng)常遇到一個(gè)需求,需要在前臺(tái)動(dòng)態(tài)添加商品SKU,然后生成表格,給每個(gè)不同的商品錄入價(jià)格與庫(kù)存等等參數(shù)。

大概效果像這樣,http://www.17sucai.com/pins/demo-show?id=8131

1561385404769.png

直接上實(shí)現(xiàn)代碼,公司一位大牛實(shí)現(xiàn)的。自己對(duì)于數(shù)組迭代嵌套循環(huán)邏輯感很差。

// 這是商品規(guī)格數(shù)據(jù)
const sskuObj = {
    color: ['green', 'red', 'yellow'],
    size: ['X1', 'X2', 'X3'],
}
// 這是我們要得到的數(shù)據(jù),然后洗一下數(shù)據(jù)就OK,給每一行添加價(jià)格庫(kù)存等數(shù)據(jù),可以配合element-ui表格使用
[ { color: 'green', size: 'X1' },
  { color: 'green', size: 'X2' },
  { color: 'green', size: 'X3' },
  { color: 'red', size: 'X1' },
  { color: 'red', size: 'X2' },
  { color: 'red', size: 'X3' },
  { color: 'yellow', size: 'X1' },
  { color: 'yellow', size: 'X2' },
  { color: 'yellow', size: 'X3' } ]

// 核心方法 

/**
 * @param {Object} skuObj 輸入的商品規(guī)格對(duì)象
 * @returns {Array} 返回規(guī)格對(duì)象窮舉的結(jié)果
 */
function j2a(skuObj) {
    const data = Object.values(skuObj)
    const newA = doExchange(data)
    const newB = []
    for (let ai = 0; ai < newA.length; ai++) {
        const newAAA = newA[ai].split('|')
        let aCount = 0
        for (const attr in skuObj) {
            newB[ai] = newB[ai] ? newB[ai] : {}
            newB[ai][attr] = newAAA[aCount]
            aCount++
        }
    }
    return newB
}

function doExchange(arr) {
    var len = arr.length
    // 當(dāng)數(shù)組大于等于2個(gè)的時(shí)候
    if (len >= 2) {
        // 第一個(gè)數(shù)組的長(zhǎng)度
        var len1 = arr[0].length
        // 第二個(gè)數(shù)組的長(zhǎng)度
        var len2 = arr[1].length
        // 2個(gè)數(shù)組產(chǎn)生的組合數(shù)
        var lenBoth = len1 * len2
        // 申明一個(gè)新數(shù)組,做數(shù)據(jù)暫存
        var items = new Array(lenBoth)
        // 申明新數(shù)組的索引
        var index = 0
        // 2層嵌套循環(huán),將組合放到新數(shù)組中
        for (var i = 0; i < len1; i++) {
            for (var j = 0; j < len2; j++) {
                items[index] = arr[0][i] + '|' + arr[1][j]
                index++
            }
        }
        // 將新組合的數(shù)組并到原數(shù)組中
        var newArr = new Array(len - 1)
        for (var newi = 2; newi < arr.length; newi++) {
            newArr[newi - 1] = arr[newi]
        }
        newArr[0] = items
        // 執(zhí)行回調(diào)
        return doExchange(newArr)
    } else {
        return arr[0]
    }
}

// 測(cè)試和使用
console.log(j2a(sskuObj))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容