let list = [
[
{"id":"83876803","name":"早晨","imgUrl":"","k_s":"s1","k":"春季"},
{"id":"97969517","name":"夏季","imgUrl":"","k_s":"s1","k":"春季"}
],
[
{"id":"60205102","name":"白1","k_s":"s2","k":"白色"}
],
[
{"id":"30012457","k":"红色","k_s":"s3","name":"红1"}
],
[
{"id":"02133206","k":"黑色","k_s":"s4","name":"黑1"}
]
]
let skuTree = [
{
k: '颜色',
k_s: 's1',
v: [
{id: '41660436', name: '白色', imgUrl: '', k_s: 's1', k: '颜色'}
]
},
{
k: '重量',
k_s: 's2',
v: [
{id: '41660426', name: '1kg', imgUrl: '', k_s: 's2', k: '重量'},
]
}
]
const f = (a, b) => [].concat(...a.map(d => b.map(e => [].concat(d, e))))
const cartesian = (a, b, ...c) => (b ? cartesian(f(a, b), ...c) : a)
const createNumberString = function (length, possibleString) {
let text = ''
const possible = possibleString || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
function generateSkuList (skuTree) {
// 根据sku tree变化重新生成sku list
// 二维数组 skuValueArray: [ [{ k_s: 's1', k: '颜色', id: '30349678', name: '红色', imgUrl: 'xxx' }, { k_s... }], [{ k_s: 's2', ... }] ]
let skuValue2DArray = [],skuList = [], newSkuList = [], withPrice = false
skuTree.forEach(tree => {
let skuValueArray = []
tree.v.forEach(valueItem => {
skuValueArray.push(Object.assign(valueItem, { k_s: tree.k_s, k: tree.k }))
})
if (skuValueArray.length) {
skuValue2DArray.push(skuValueArray)
}
})
if (!skuValue2DArray.length) {
this.setData({ skuList: [], totalStock: 0 })
return []
}
// 笛卡尔组合 二维数组结果(如果只有一级规格s1,则数组对象是Object不是数组)
const cartesianCombination = cartesian(...skuValue2DArray)
console.log('cartesianCombination',cartesianCombination)
let totalStock = 0
cartesianCombination.forEach(ccArray => {
let skuListItem = { stock_num: 0 }
for (var i = 1; i <= 5; i++) {
const sn = `s${i}`
const ccItem = Array.isArray(ccArray) ? ccArray.find(cc => cc.k_s === sn) :
(ccArray && ccArray.k_s === sn ? ccArray : null)
if (ccItem) {
skuListItem[sn] = ccItem.id
const keyValueName = ccItem.k + ':' + ccItem.name
skuListItem[sn + 'Name'] = keyValueName
skuListItem['name'] = (skuListItem['name'] ? skuListItem['name'] + ',' : '') + keyValueName
} else {
skuListItem[sn] = '0'
}
}
// skuList 如果已经存在,则使用其 id(skuId)和 stock_num,否则赋值新的 skuId
const foundSkuListItem = skuList.find(sl => sl.s1 === skuListItem.s1 && sl.s2 === skuListItem.s2
&& sl.s3 === skuListItem.s3 && sl.s4 === skuListItem.s4 && sl.s5 === skuListItem.s5)
if (foundSkuListItem) {
skuListItem.id = foundSkuListItem.id
skuListItem.stock_num = parseInt(foundSkuListItem.stock_num || 0)
if (withPrice) {
// 单位:分
skuListItem.originalPrice = parseInt(foundSkuListItem.originalPrice || 0)
skuListItem.price = parseInt(foundSkuListItem.price || 0)
}
} else {
skuListItem.id = createNumberString(8)
}
totalStock += parseInt(skuListItem.stock_num)
newSkuList.push(skuListItem)
})
return newSkuList
}
// console.log(generateSkuList(skuTree))
console