0

I have an array of data like this one

[
  {
    "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
]

and I'm trying to get rid of all parents data & catch & merge only child items like this one:

[
  {
    "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"
  }
]

but after reading normalizr documentation I'm a little bit confused because I couldn't find this kind of example, so can anyone suggest me is it possible to make with normalizr or any better idea?

Thanks

  • Does this answer your question? [Find by key deep in a nested array](https://stackoverflow.com/questions/15523514/find-by-key-deep-in-a-nested-array) – GBra 4.669 Feb 19 '21 at 18:55

1 Answers1

0

Recusrion is what you need here:

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));
gorak
  • 5,233
  • 1
  • 7
  • 19