假设有options1如下:
const options1 = [
{
description: 'aa',
name: 'label',
},
{
description: 'bb',
name: 'value',
},
{
description: undefined,
name: 'children',
children: [
[
{
description: 'cc',
name: 'label',
},
{
description: 'dd',
name: 'value',
},
{
description: undefined,
name: 'children',
children: [
[
{
description: 'ee',
name: 'label',
},
{
description: 'ff',
name: 'value',
},
]
]
}
],
[
{
description: 'gg',
name: 'label',
},
{
description: 'hh',
name: 'value',
},
]
],
},
];
再有options2:
tips: options1和options2的数据格式一样
const options2 = [
{
description: '11',
name: 'label',
},
{
description: '22',
name: 'value',
},
{
description: undefined,
name: 'children',
children: [
[
{
description: '33',
name: 'label',
},
{
description: '44',
name: 'value',
},
{
description: undefined,
name: 'children',
children: [
[
{
description: '55',
name: 'label',
},
{
description: '66',
name: 'value',
},
]
]
}
]
],
},
];
现在需要将options = [options1, options2]进行处理,得到下面的结果:
[
[
{
label: 'aa',
value: 'bb',
children: [
[
{
label: 'cc',
value: 'dd',
children: [
[
{
label: 'ee',
value: 'ff',
}
]
]
}
],
[
{
label: 'gg',
value: 'hh',
}
]
]
}
],
[
{
label: '11',
value: '22',
children: [
[
{
label: '33',
value: '44',
children: [
[
{
label: '55',
value: '66'
}
]
]
}
]
]
}
]
]
处理思路:
options的数据格式其实和children是一样的,都是一个二维数组,这个二维数组的元素都是一维数组,并且一维数组的元素都是由2个或者3个对象构成的,即name为label的对象,name为value的对象,name为children的对象。
所以可以对递归进行拆解,当遇到name为children的对象时,调用父函数,当name为label或者value时,调用子函数。在子函数中返回包含label, value, children为key的对象。
const options = [options1, options2];
const fn = (options) => {
let res = {};
for(let i = 0; i < options.length; i++){
if(options[i].name === 'label'){
res.label = options[i].description;
}
if(options[i].name === 'value'){
res.value = options[i].description;
}
if(options[i].name === 'children'){
res.children = mainFn(options[i].children);
}
}
return res;
}
const mainFn = (options) => {
let resArr = [];
for (let i = 0; i < options.length; i++) {
resArr.push(fn(options[i]));
}
return resArr;
}
console.log(mainFn(options))