数组里有children,如何获取数组所有对象中某个key对应的值

[
    {
        id: 1,
        age: 23,
        name: bear,
        children: [
            {
                id: 2,
                age: 24,
                name: bear1
            },
        ],
    },
    {
        id: 3,
        age: 26,
        name: bear2,
        children: [],
    }
]

如何获取里面所有的id值,包括children里的

阅读 7k
6 个回答
let a = [{id:1,children:[{id:2}]},{id:3,children:[]}]
    function func(arr){
      return arr.reduce((a, b) => {
        let res = [...a,b.id];
        if (b.children) res = [...res, ...func(b.children)];
        return res;
      }, []);
    }
   console.log(func(a))
const getIds = (arr) => {
  const ans = [];

  const dfs = (root, ans) => {
    let neighbor;
    if (Array.isArray(root)) {
      neighbor = root;
    } else {
      ans.push(root.id);
      neighbor = root.children;
    }

    if (!neighbor) return;

    for (let i = 0; i < neighbor.length; ++i) {
      dfs(neighbor[i], ans);
    }
  };

  dfs(arr, ans);

  return ans;
};

这个是对象遍历查询的问题,之所以麻烦,是因为数据结构的多样性,此外你的问题是你没有说数据如何输出,或者说数据要怎么用。

已参与了 SegmentFault 思否「问答」打卡,欢迎正在阅读的你也加入。
      const getIds = function(arr) {
        const res = arr.reduce((prev, next) => {
          if (next.id) prev.push(next.id);
          if (next.children && next.children.length) return prev.concat(getIds(next.children));
          return prev;
        }, []);
        return res;
      };
      const res = getIds(arr);
      console.log(res);
function getKeys(list, key) {
    return list.reduce((res, v) => {
        if(v.children && v.children.length) res = res.concat(getKeys(v.children,key))
        res.push(v[key]);
        return res;
    }, [])
}
getKeys([
    {
        id: 1,
        age: 23,
        name: 'bear',
        children: [
            {
                id: 2,
                age: 24,
                name: 'bear1'
            },
        ],
    },
    {
        id: 3,
        age: 26,
        name: 'bear2',
        children: [],
    }
], 'id')
已参与了 SegmentFault 思否「问答」打卡,欢迎正在阅读的你也加入
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题