如何从嵌套数组中获取单个名称 属性?

how to fetch the single name property from nested array?

我正在处理 Angular 项目,我需要从给定的嵌套数组对象中获取名称 属性。 我尝试使用 lodash 映射函数 _.map('ArrayName',(o)=>o.name); ,结果我只收到 [ Peter, Andy ] 。我想要所有名字 属性 [Peter, Andy, Mills, mac, Teddy] 都这样。谁能指导我怎么做。

[{
"id": "1",
"name": "Peter",
"children": []}
,{
"id": "2",
"name": "Andy",
"children": [
  {
    "id": "3",
    "name": "Mills",
    "children": []
  },
  {
    "id": "4",
    "name": "Mac",
    "children": [
      {
        "id": "5",
        "name": "Teddy",
        "children": []
      }
    ]
  }
]}]

您需要递归访问嵌套的 children 数组。

这是一个使用 Array.prototype.flatMap() and spread syntax 递归迭代每个子数组并展平结果的示例。

const input = [{ "id": "1", "name": "Peter", "children": [] }, { "id": "2", "name": "Andy", "children": [{ "id": "3", "name": "Mills", "children": [] }, { "id": "4", "name": "Mac", "children": [{ "id": "5", "name": "Teddy", "children": [] }] }] }];

const recursivelyGetProp = (arr, prop) => (
  arr.flatMap(({ children, [prop]: p }) =>
    [p, ...(children.length ? recursivelyGetProp(children, prop) : [])]
  ));

console.log(recursivelyGetProp(input, 'name'));