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)

多层级数组如何根据id匹配某个字段的值

{"code":0,"msg":"成功","data":[{"children":[{"children":[],"id":2,"code":"S1","name":"销售部1"},{"children":[],"id":3,"code":"S2","name":"销售部2"}],"id":1,"code":"S","name":"销售部"},{"children":[{"children":[],"id":8,"code":"C1","name":"生产部1"}],"id":4,"code":"C","name":"生产部"},{"children":[],"id":5,"code":"Q","name":"质检部"},{"children":[],"id":6,"code":"W","name":"财务部"},{"children":[],"id":7,"code":"G","name":"采购部"}],"total":0}


  • 请问上面格式的数组如何根据id匹配code,两个for循环的会报错

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

1 Reply

0 votes
by (71.8m points)
var response = {"code":0,"msg":"成功","data":[{"children":[{"children":[],"id":2,"code":"S1","name":"销售部1"},{"children":[],"id":3,"code":"S2","name":"销售部2"}],"id":1,"code":"S","name":"销售部"},{"children":[{"children":[],"id":8,"code":"C1","name":"生产部1"}],"id":4,"code":"C","name":"生产部"},{"children":[],"id":5,"code":"Q","name":"质检部"},{"children":[],"id":6,"code":"W","name":"财务部"},{"children":[],"id":7,"code":"G","name":"采购部"}],"total":0}



function findNode(list, cb) {
  for(const item of list) {
    if(cb(item)) return item
    if(Array.isArray(item.children)) {
      const child = findNode(item.children, cb)
      if(child) return child
    }
  }
  return null;
}

var item = findNode(response.data, item => item.id == 2)
console.log(item)

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

...