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
4.2k views
in Technique[技术] by (71.8m points)

vue/react/js for循环及map方法代码精简问题

原始data↓

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 }]

假设有这样一个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

现在的代码↓

for (const i in data) {
        if (!data[i].children || data[i].children.length == 0) {
          data[i].pid = ""
          data[i].sort = i
        }
      }
      
let b = data.flatMap(i => {
        i.children.map((j, index) => { j.pid = i.id; j.sort = index; j.menuType = 0 });
        let a = i.children; delete i.children; a.unshift(i);
        return a
      });
      console.log(b)

现在的代码可以完成上诉需求,但是我觉得太复杂了想优化或者精简,比如说把上面的for循环放在下面的“let b”里面,所以请教下各位该怎么写

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


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

1 Answer

0 votes
by (71.8m points)
const 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 }
        ]
      }
    ];
    const result = data.reduce((a, b) => {
      const func = obj => {
        let res = [obj];
        if (obj.children)
          res = [
            ...res,
            ...obj.children.map((item, i) => ({
              ...item,
              pid: obj.id,
              sort: i
            }))
          ];
        return res;
      };
      return [...a, ...func(b)];
    }, []);
    console.log(result);

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

...