Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

js 三重遍历问题

这是一个data
image
我们打开一个来看看,是这样的,里面有children
image
然后再把children打开
image
然后再打开里面的其中一个对象,里面还有一层children,不过是为空
image

这就是这个data的数据结构,现在我需要的是遍历这个data里的所有children,然后如果这些children里的appId=pid话,然后就把这个children的数据放在这个appId的children,并删除外面那条children,简单的来说就是剪切→粘贴

先感谢大神们的解答


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

1 Reply

0 votes
by (71.8m points)
var list = [
  {
    id: '1',
    appName: 'name',
    children: [
      {
        id: '11',
        pid: '123',
        appId: '123',
        children: []
      },
      {
        id: '22',
        pid: '456',
        appId: '456',
        children: []
      },
      {
        id: '33',
        pid: '33434',
        appId: '456',
        children: []
      },
    ]
  }
]

function map(list) {
  return list.reduce((res, item) => {
    if(Array.isArray(item.children) && item.children.length) res.push({...item, children: map(item.children)})
    else if(item.pid === item.appId) res.push(item)
    return res;
  }, []);
}

map(list)

是这样?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...