JavaScript中的递归:对象数组里根据id获取name,对象可能有children属性

let array = [
  {
    id: 1,
    name: "001",
    children: [
      {
        id: 2,
        name: "002",
      },
    ],
  },
  { id: 3, name: "003", children: [] },
];

function getFlatArr(arr) {
  return arr.reduce((a, item) => {
    let flatArr = [...a, item];
    if (item.children) {
      flatArr = [...flatArr, ...getFlatArr(item.children)];
    }
    return flatArr;
  }, []);
}
console.log(getFlatArr(array));

function getNameByIdFromArr(arr, id) {
  return getFlatArr(arr).find((item) => item.id === id).name;
}
console.log(getNameByIdFromArr(array, 2));

 

posted @ 2021-09-30 13:46  starlog  阅读(1469)  评论(0编辑  收藏  举报