Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

js for循环把tree结构转换为list

假设有这样一个data,我需要把children提取出来与外面那层同级,然后去除children,也就是说我需要整个data只有一级只有一层,然后这里面children里的pid要等于父级的id。
sort排序从0开始,比如label为“1”的父级底下的children里有两条数据,这两条children里的sort从0开始到1。
同样的,如果同时另外一个label为“2”的父级底下的children里有两条数据,他这两条children里的sort也是从0开始到1。

ps:data中的其他key、value不可动,要保留住,例如label

原始↓ :

data:  [{
          id: '1',
          label: '1',
          sort: 1,
          children:[{ pid: null, label: '1-1', sort: null },{ pid: null, label: '1-2', sort: null },]
        },{
          id: '2',
          label: '2',
          sort: 2,
          children:[{ pid: null, label: '2-1', sort: null },{ pid: null, label: '2-2', sort: null },]
        }]

理想↓:

       [{ id: '1', label: '1', sort: 1 },
        { pid: '1', label: '1-1', sort: 0 },
        { pid: '1', label: '1-2', sort: 1 },
        { id: '2', label: '2', sort: 2 },
        { pid: '2', label: '2-1', sort: 0 },
        { pid: '2', label: '2-2', sort: 1 }]

说的可能有点乱,大婶们如果没听懂我在说啥请轻喷,麻烦你们了!!


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

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)
let data = [{
          id: '1',
          label: '1',
          sort: 1,
          children:[{ pid: null, label: '1-1', sort: null },{ pid: null, label: '1-2', sort: null },]
        },{
          id: '2',
          label: '2',
          sort: 2,
          children:[{ pid: null, label: '2-1', sort: null },{ pid: null, label: '2-2', sort: null },]
        }]
        
       let b = data.flatMap(i=>{i.children.map((j,index)=>{j.pid = i.id;j.sort=index});let a = i.children;delete i.children;a.unshift(i);console.log(a);return a});
       console.log(b);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...