待处理数据 (this.specs)
[
{
"label": "颜色",
"isInput": false,
"inputText": "",
"item": [
{
"label": "白色",
"icon": "http://xxx/20170906db49873acaaf4ff79b13fbc199f97025.jpg"
},
{
"label": "卡其色",
"icon": "http://xxx/201709060f9949b868e5461bb72b84e42d2c12c3.jpg"
}
]
},
{
"label": "第二层",
"isInput": false,
"inputText": "",
"item": [
"第二层类别1",
"第二层类别2"
]
},
{
"label": "第三层",
"isInput": false,
"inputText": "",
"item": [
"第三层类别1",
"第三层类别2"
]
}
]
想得到的数据模型 (this.specList)
[
{
"title": "颜色",
"label": "白色",
"item": [
{
"title": "第二层",
"label": "第二层类别1",
"item": [
{
"title": "第三层",
"label": "第三层类别1",
"item": {
"price": 1,
"stock": 2,
"value": 3,
"sales": 4
}
},
{
"title": "第三层",
"label": "第三层类别2",
"item": {
"price": 1,
"stock": 2,
"value": 3,
"sales": 4
}
}
]
},
{
"title": "第二层",
"label": "第二层类别2",
"item": [
{
"title": "第三层",
"label": "第三层类别1",
"item": {
"price": 1,
"stock": 2,
"value": 3,
"sales": 4
}
},
{
"title": "第三层",
"label": "第三层类别2",
"item": {
"price": 1,
"stock": 2,
"value": 3,
"sales": 4
}
}
]
}
],
"icon": "xxx/20170906db49873acaaf4ff79b13fbc199f97025.jpg"
},
{
"title": "颜色",
"label": "卡其色",
"item": [
{
"title": "第二层",
"label": "第二层类别1",
"item": [
{
"title": "第三层",
"label": "第三层类别1",
"item": {
"price": 1,
"stock": 2,
"value": 3,
"sales": 4
}
},
{
"title": "第三层",
"label": "第三层类别2",
"item": {
"price": 1,
"stock": 2,
"value": 3,
"sales": 4
}
}
]
},
{
"title": "第二层",
"label": "第二层类别2",
"item": [
{
"title": "第三层",
"label": "第三层类别1",
"item": {
"price": 1,
"stock": 2,
"value": 3,
"sales": 4
}
},
{
"title": "第三层",
"label": "第三层类别2",
"item": {
"price": 1,
"stock": 2,
"value": 3,
"sales": 4
}
}
]
}
],
"icon": "xxx/201709060f9949b868e5461bb72b84e42d2c12c3.jpg"
}
]
处理方法
递归处理
initStock(index, item = this.formModel) {
if (index >= 0) {
const arr = []
this.specs[index].item.forEach(el => {
const obj = {
title: this.spec[index].label,
label: el.label || el,
item
}
if (index === 0) {
obj.icon = el.icon;
}
arr.push(obj);
})
this.initStock(--index, arr);
} else {
this.specList = item;
}
}
常规处理
initInventory() {
if (this.isEdit) {
this.isEdit = false;
return;
}
//* 库存表格对象重建
const arr = [];
//* 构建对象
function initObject(el) {
el.item = {};
//* 价格
el.item.price = '';
//* 库存
el.item.stock = '';
//* 成本
el.item.value = '';
//* 销量
el.item.sales = 0;
}
if (this.specs[0].item) {
this.specs[0].item.forEach(item1 => {
const obj1 = {};
obj1.label = item1.label || item1;
if (this.specs[1]) {
obj1.item = [];
this.specs[1].item.forEach(item2 => {
const obj2 = {};
obj2.label = item2;
if (this.specs[2]) {
obj2.item = [];
this.specs[2].item.forEach(item3 => {
const obj3 = {};
//* 标签名
obj3.label = item3;
initObject(obj3);
obj2.item.push(obj3);
})
} else {
initObject(obj2);
}
obj1.item.push(obj2);
});
} else {
initObject(obj1);
}
arr.push(obj1);
});
}
this.specList = arr;
}
效果图
8e47ec0f77cb0da5bb456352b38309f25117b9ec_1_690x313.png两种方法得出来的结果是一样的,区别在于处理的方式不一样。
用递归方法处理的数据最后会导致商品价格等信息指向同一个引用
网友评论