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

js/vue/react 如何在这种数据格式里判断是否有相同的id

数据格式 ↓

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 id = '114' //判断这个id是否在data中存在

如上所示数据结构,要判断的id可能在第一层children里面,也可能在第二层children里面,也可能不在children里面,我如何操作才能判断 “这个id” 是否存在这个data里呢

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


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

1 Answer

0 votes
by (71.8m points)

树的遍历。

function some(node, id) {
    return node && node.some(node => {
        return node.id === id || some(node.children, id);
    })
}

// TEST
some(data, '114') // true
some(data, '1140') // false

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

2.1m questions

2.1m answers

60 comments

57.0k users

...