js/vue/react 如何把这种数据结构格式的data 转为同一个对象
数据格式 ↓
let data = [{
name:'水果大全',
id:'111',
children:[{
name:'浆果类',
id:'112',
children:[{ //从这一层提取
name:'草莓',
id:'113'
},{
name:'桑椹',
id:'114'
},{
name:'黑莓',
id:'115'
}]
},{
name:'柑橘类',
id:'116',
children:[{ //从这一层提取
name:'橘子',
id:'117'
},{
name:'橙子',
id:'118'
}]
}]
},{
name:'奥特曼大全',
id:'119',
children:[{
name:'昭和类',
id:'120',
children:[{ //从这一层提取
name:'杰克',
id:'121'
},{
name:'泰罗',
id:'122'
},{
name:'艾斯',
id:'123'
}]
},{
name:'平成类',
id:'124',
children:[{ //从这一层提取
name:'迪迦',
id:'125'
},{
name:'盖亚',
id:'126'
}]
}]
}]
理想效果↓
let data = [{
name: '草莓',
id: '113'
}, {
name: '桑椹',
id: '114'
}, {
name: '黑莓',
id: '115'
}, {
name: '橘子',
id: '117'
}, {
name: '橙子',
id: '118'
}, {
name: '杰克',
id: '121'
}, {
name: '泰罗',
id: '122'
}, {
name: '艾斯',
id: '123'
}, {
name: '迪迦',
id: '125'
}, {
name: '盖亚',
id: '126'
}]
如上所示,从第二层children提取并转为在一个对象里面,我该怎么操作呢。
在这里先谢谢各位大神大哥们的解答,小弟感激不尽!
回答
data.map(item=>item.children.map(child=>child.children)).flat(Infinity)
function loop(data, arr) {
for (var item of data) {
if (item.children) {
arr = loop(item.children, arr)
} else {
arr = arr.concat(data)
}
}
return arr
}
var filterData = loop(data, []);
// 去重
var temp = {}
var result = filterData.reduce(function(sum, arrItem) {
if (!temp[arrItem.id]) {
temp[arrItem.id] = arrItem.id
sum.push(arrItem)
}
return sum
}, [])
// console.log('result', result)
THE END
二维码