多层数据结构对象遍历问题

 list = [
     {
      id: 1,
      label: 'a',
      children: [{
        id: 4,
        label: 'b',
        children: [{
          id: 9,
          label: 'c'
        }, {
          id: 10,
          label: 'd'
        }]
      }]
    }
 ]
 
 怎么根据label = c的条件 拿到 id为9的这条属性
阅读 2.5k
3 个回答
const find = (list, label) => {
  let result;
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (item.label === label) {
      return result = item;
    } else {
      if (item.children) {
        result = find(item.children, label);
      }
    }
  }
  return result;
};

const result = find(list, "c");
console.log(result);

建议初始遍历一次生成一个label-id Map表,不然每次label变化都需要遍历。

  • 递归,一层层去遍历。
    let item = {};
    let findLabel = data => {
      data.forEach(el => {
        if (el.label == 'c') {
          return item = el;
        } else {
          if (el.children != undefined) {
            findLabel(el.children);
          }
        }
      });
    };
    findLabel(list)
    console.log(item);
推荐问题