Normalizr:规范化深层嵌套项目

Normalizr: normalize deep nested items

我有一组这样的数据

[
  {
    "id": "root_01",
    "parents": [
      {
        "id": "parent_1",
        "childrens": [
          {
            "id": "child_01",
            "name": "ABC",
            "group": "group_a"
          },
          {
            "id": "child_02",
            "name": "BBC",
            "group": "group_b"
          }
        ]
      },
      {
        "id": "parent_2",
        "childrens": [
          {
            "id": "child_03",
            "name": "CCD",
            "group": "group_a"
          },
          {
            "id": "child_04",
            "name": "EEF",
            "group": "group_c"
          }
        ]
      }
    ]
  },
  {} // same as previous
]

并且我正在尝试删除所有父项数据并仅捕获并合并像这样的子项:

[
  {
    "id": "child_01",
    "name": "ABC",
    "group": "group_a"
  },
  {
    "id": "child_02",
    "name": "BBC",
    "group": "group_b"
  },
  {
    "id": "child_03",
    "name": "CCD",
    "group": "group_a"
  },
  {
    "id": "child_04",
    "name": "EEF",
    "group": "group_c"
  }
]

但是在阅读 normalizr 文档后我有点困惑,因为我找不到这种例子,所以有人可以建议我可以使用 normalizr 或更好的主意吗?

谢谢

Recusrion 是您需要的:

const arr = [ { "id": "root_01", "parents": [ { "id": "parent_1", "childrens": [ { "id": "child_01", "name": "ABC", "group": "group_a" }, { "id": "child_02", "name": "BBC", "group": "group_b" } ] }, { "id": "parent_2", "childrens": [ { "id": "child_03", "name": "CCD", "group": "group_a" }, { "id": "child_04", "name": "EEF", "group": "group_c" } ] } ] }];

const flatten = arr => arr.flatMap(o=>o.parents ? flatten(o.parents) : o.childrens ? flatten(o.childrens) : o);

console.log(flatten(arr));