鍍金池/ 問(wèn)答/HTML/ 求幫解決一個(gè)JS 遞歸的 查找值的問(wèn)題

求幫解決一個(gè)JS 遞歸的 查找值的問(wèn)題

需求:遞歸從下面的數(shù)據(jù)中找到某一個(gè)值。
例如:傳入a1 ,找到a1所有在位置,并添加一個(gè)屬性 expand: true,
因?yàn)楹笈_(tái)返回的數(shù)據(jù)層級(jí)不確定,得要遞歸才可以。

export const json = [{
    "name": "測(cè)試1",
    "children": []
  },
  {
    "name": "測(cè)試2",
    "children": [{
        "name": "A區(qū)",
        "children": [{
            "name": "a1",
            "children": null
          },
          {
            "name": "a2",
            "children": null
          },
        ]
      },
      {
        "name": "B區(qū)",
        "children": [{
            "name": "b1",
            "children": null
          },
          {
            "name": "b2",
            "children": null
          },
        ]
      }
    ]
  },
]
回答
編輯回答
遲月

使用數(shù)組解構(gòu)似乎更方便。

let [, {children: [{children}]}] = json
let index = children.findIndex(obj => obj.name === 'a1')
children[0].expand = true

是不是很簡(jiǎn)單,捂臉逃走。

2017年5月2日 09:16
編輯回答
孤島

function addExpand(arr, find){
  for(let k in arr){
   let item = arr[k]
   if(typeof item === 'object'){
      addExpand(item, find);
    } else{
      if (item == find) {
         arr.expand = true
      }
    }
  }
  return arr
}

let nJson = addExpand(json, 'a1')
2018年7月25日 14:54
編輯回答
做不到
function recursive(data,name){
    data.map(function(item){
        if(item.name !== name &&item.children && item.children.length){
            recursive(item.children, name);
        }
        else if(item.name === name){
            item.expand = true;
        }
        else{}
    })
}
2017年12月5日 20:15
編輯回答
櫻花霓
function findTarget(source, targetName) {
  if (source && source.length) {
    for (let item of source) {
      if (item.name === targetName) {
        item.expand = true;
      } else if (item.children && item.children.length){
        findTarget(item.children, targetName);
      }
    }
  }
}

findTarget(json, "a1");
2018年5月12日 05:45
編輯回答
青瓷
function search(obj, name, namePath = []) {
  for (let i = 0, len = obj.length; i < len; i++) {
    let item = obj[i]
    if (item.name === name) {
      namePath.push(name)
      item.expand = true
      return {
        has: true,
        namePath
      }
    } else if (item.children && item.children.length) {
      namePath.push(item.name)
      let result = search(item.children, name, namePath)
      if (result.has) return {has: true, namePath}
      namePath.pop()
    }
  }
  return {
    has: false
  }
}

console.log(search(json, "測(cè)試2")) // {has: true, namePath: ["測(cè)試2"]}
console.log(search(json, "A區(qū)")) // {has: true, namePath: ["測(cè)試2", "A區(qū)"]}
console.log(search(json, "a2")) // {has: true, namePath: ["測(cè)試2", "A區(qū)", "a2"]}
console.log(search(json, "b2")) // {has: true, namePath: ["測(cè)試2", "B區(qū)", "b2"]}
console.log(search(json, "c2")) // {has: false}
2017年7月9日 21:10