Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k views
in Technique[技术] by (71.8m points)

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提取并转为在一个对象里面,我该怎么操作呢。

在这里先谢谢各位大神大哥们的解答,小弟感激不尽!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
data.map(item=>item.children.map(child=>child.children)).flat(Infinity)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...