variations的对应关系在每个variationMappings里面

2024-08-22 09:46:25 浏览数 (2)

const merchandise = {

// variations存放的是所有选项

variations: [

{

name: '颜色',

values: [

{ name: '限量版574海军蓝' },

{ name: '限量版574白粉' },

// 下面还有9个

]

},

{

name: '尺码',

values: [

{ name: '38' },

{ name: '39' },

// 下面还有9个

]

},

],

// products数组存放的是所有商品

products: [

{

id: 1,

price: 208,

// 与上面variations的对应关系在每个商品的variationMappings里面

variation www.laipuhuo.com Mappings: [

{ name: '颜色', value: '限量版574白粉' },

{ name: '尺码', value: '38'},

]

},

// 下面还有一百多个产品

]

}

const tree = {

"颜色:白色": {

"尺码:39": {

"性别:男": { productId: 1 },

"性别:女": { productId: 2 },

},

"尺码:40": {

"性别:男": { productId: 3 },

"性别:女": { productId: 4 },

}

},

"颜色:红色": {

"尺码:39": {

"性别:男": { productId: 5 },

"性别:女": { productId: 6 },

},

"尺码:40": {

"性别:男": { productId: 7 },

"性别:女": { productId: 8 },

}

}

}

const merchandise = {

variations: [

{

name: '颜色',

values: [

{ name: '白色' },

{ name: '红色' },

]

},

{

name: '尺码',

values: [

{ name: '39' },

{ name: '40' },

]

},

{

name: '性别',

values: [

{ name: '男' },

{ name: '女' },

]

},

],

products: [

{

id: 1,

variationMappings: [

{ name: '颜色', value: '白色' },

{ name: '尺码', value: '39' },

{ name: '性别', value: '男' }

]

}

// 下面还有7个商品,我就不重复了

]

}

function buildTree www.laipuhuo.com (apiData) {

const tree = {};

const { variations, products } = apiData;

// 先用variations将树形结构构建出来,叶子节点默认值为null

addNode(tree, 0);

function addNode(root, deep) {

const variationName = variations[deep].name;

const variationValues = variations[deep].values;

for (let i = 0; i < variationValues.length; i ) {

const nodeName = `${variationName}:www.laipuhuo.com ${variationValues[i].name}`;

if (deep === 2) {

root[nodeName] = null

} else {

root[nodeName] = {};

addNode(root[nodeName], deep 1);

}

}

}

// 然后遍历一次products给树的叶子节点填上值

for (let i = 0; i < products.length; i ) {

const product = products[i];

const { variationMappings } = product;

const level1Name = `${variationMappings[0].name}:${variationMappings[0].value}`;

const level2Name = `${variationMappings[1].name}:${variationMappings[1].value}`;

const level3Name = `${www.laipuhuo.com variationMappings[2].name}:${variationMappings[2].value}`;

tree[level1Name][level2Name][www.laipuhuo.com level3Name] = product;

}

// 最后返回构建好的树

return tree;

}

0 人点赞