多层级数组如何根据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循环的会报错

回答

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)

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

贴出来我自己的解决方案吧
先将多层级数组扁平化处理
// 扁平化处理参考https://segmentfault.com/q/1010000016781339 第二个回答

function arrayChildrenFlatten(array, { childrenKeys, flattenParent, flattenParentKey } = {}) {

childrenKeys = childrenKeys || ['children']

flattenParent = flattenParent || []

flattenParentKey = flattenParentKey || 'flattenParent'

const result = []

array.forEach(item => {

const flattenItem = JSON.parse(JSON.stringify(item))

flattenItem[flattenParentKey] = flattenParent

result.push(flattenItem)

childrenKeys.forEach(key => {

if (item[key] && Array.isArray(item[key])) {

const children = arrayChildrenFlatten(item[key], {

childrenKeys,

flattenParent: [...flattenParent, item],

flattenParentKey

})

result.push(...children)

}

})

})

return result

}

然后再去查询一遍

this.form.departCode = this.findNode(arrayChildrenFlatten(dataArray), newVal)

// dataArray是原数组,newVal是要查询的值

findNode(data, newVal) {

if (data.find(item => item.id == newVal)) {

return data.find(item => item.id == newVal).code

} else {

return '暂无'

}

}

一楼大佬的解决方案更优,赞!

以上是 多层级数组如何根据id匹配某个字段的值 的全部内容, 来源链接: utcz.com/a/82829.html

回到顶部