例: ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']`
想得到:
[
{
name:'动物',
children:[
{name:'昆虫'
children:[
{name:'蚂蚁'},
{name:'蝴蝶'}
]
}
]
},
{
同上
}
]
例: ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']`
想得到:
[
{
name:'动物',
children:[
{name:'昆虫'
children:[
{name:'蚂蚁'},
{name:'蝴蝶'}
]
}
]
},
{
同上
}
]
var arr = ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']
var list = [], res = []
arr.forEach(child => {
var items = child.split('-');
var lis = {
name: items[0],
children: [{
name: items[1],
children: [{
name: items[2]
}]
}]
}
list.push(lis);
})
list.forEach(lis => {
handle(res, lis)
})
function handle (res, lis) {
var curItem = res.find(item => item.name === lis.name)
if (!curItem) {
res.push(lis)
} else {
handle (curItem.children, lis.children[0])
}
}
console.log(JSON.stringify(res, null, ' '));
var arr = ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']
let newArr = [];
let getObjByName = function(arr,name){
let newA = arr.filter(a => {
return a.name === name;
});
let ret = {};
if(newA.length === 0){
ret = {children:[],name:name};
arr.push(ret);
} else {
ret = newA[0];
}
return ret;
}
arr.forEach( ar => {
let a = ar.split('-');
let children1 = getObjByName(newArr,a[0]);
let children2 = getObjByName(children1.children,a[0]);
children2.children.push({name:a[2]});
children2.name = a[1];
});
console.log(JSON.stringify(newArr, null, ' '));
13 回答12.8k 阅读
8 回答2.6k 阅读
2 回答5.1k 阅读✓ 已解决
7 回答1.9k 阅读
3 回答2.2k 阅读✓ 已解决
5 回答850 阅读
3 回答1.1k 阅读✓ 已解决
测试:
输出: