基于固定的SKU數據結構的組合,輸出A、B、C等系列的多類組合。
function generateCombinations(source) {
const combinations = [];
function generateHelper(index, current, spDataList) {
if (index === source.length) {
combinations.push({...current, spDataList, spData: JSON.stringify(spDataList)});
return;
}
const item = source[index];
for (let i = 0; i < item.inputSelectArr.length; i++) {
const newCurrent = {...current};
newCurrent[`id_${item.id}`] = item.inputSelectArr[i].value;
newCurrent.enable = 1
if (index == 0)
newCurrent.pic = item.inputSelectArr[i].pic;
const newSpData = [...spDataList, {key: item.name, value: item.inputSelectArr[i].value}];
generateHelper(index + 1, newCurrent, newSpData);
}
}
generateHelper(0, {}, []);
return combinations;
}
那如果需要通過組合后的數據來反轉原始數據呢?
我們來看下:
1、首先,觀察生成的組合列表,找到其中的共同點和區別。從代碼中可以看出,生成的每個組合都包含以下幾個屬性:
id_${item.id}:表示某個輸入項的選中值;
spDataList:表示整個組合的所有輸入項及其選中值;
spData:表示 spDataList 序列化后的字符串;
enable:表示該組合是否可用;
pic:表示組合對應的圖片路徑。
可以看到,每個組合都包含一個輸入項的選中值,而輸入項有多個,每個輸入項有多個選項,因此需要確定原始數據結構中輸入項和其選項的屬性。
2、其次,確定原始數據結構中輸入項和其選項的屬性。從代碼中可以看出,原始數據結構應該包含一個數組,每個數組元素代表一個輸入項,其中每個輸入項應該包含以下屬性:
id:表示該輸入項的唯一標識符;
name:表示該輸入項的名稱;
inputSelectArr:表示該輸入項的選項,是一個數組,每個數組元素代表一個選項,其中每個選項應該包含以下屬性:
value:表示該選項的值;
pic:表示該選項對應的圖片路徑。
3、最后,根據生成的組合列表和確定的原始數據結構,反推原始數據結構。根據組合列表中的 spDataList 屬性,可以確定原始數據結構中的每個輸入項的名稱和對應的選項值;根據組合列表中的 enable 屬性,可以確定原始數據結構中每個組合是否可用;根據組合列表中的 pic 屬性,可以確定原始數據結構中每個組合對應的圖片路徑。
代碼如下:
function reverseGenerateCombinations(combinations) {
// 從第一個組合中獲取輸入項的名稱
const inputNames = combinations[0].spDataList.map(data => data.key);
// 根據輸入項名稱創建空的輸入項列表
const inputs = inputNames.map(name => ({ id: name, name, inputSelectArr: [] }));
// 遍歷每個組合,獲取每個輸入項的選項值和對應的圖片路徑
combinations.forEach(({ spDataList, enable, pic }) => {
spDataList.forEach(({ key, value }) => {
// 找到對應的輸入項
const input = inputs.find(input => input.id === key);
// 如果該選項還不存在,則添加該選項
if (!input.inputSelectArr.some(option => option.value === value)) {
input.inputSelectArr.push({ value, pic });
}
});
});
return inputs;
}