Node JS Nested Array Transformation

I am trying to transform following array but it’s only transforming single level. multiple remain same want to remove entity for each level of object.

I have used the map to modify object not sure if there are others method for the multi level

Here is the array


const source = [
  {
    "block_id": 1,
    "entity": 100,
    "block_name": "test 1",
    "children": [
      {
        "block_id": 2,
        "entity": 101,
        "block_name": "test 2",
        "children": [
          {
            "block_id": 3,
             "entity": 105,
            "block_name": "test 2",
          }

        ]
      }
      
    ],
  }
]

Tried following code to transform

function trans(item) {
  const items = Array.isArray(item) ? item : [item];
    return items.map( t => {
        return { block_id: t.block_id, block_name: t.block_name, children: t.children };
    });
}

I am getting following

Output

[
  {
    "block_id": 1,
    "block_name": "test 1",
    "children": [
      {
        "block_id": 2,
        "entity": 101,
        "block_name": "test 2",
        "children": [
          {
            "block_id": 3,
            "entity": 105,
            "block_name": "test 2",
          }

        ]
      }
      
    ],
  }
]

Expected

[
  {
    "block_id": 1,
    "block_name": "test 1",
    "children": [
      {
        "block_id": 2,
        "block_name": "test 2",
        "children": [
          {
            "block_id": 3,
            "block_name": "test 2",
          }

        ]
      }
      
    ],
  }
]

Please help

Leave a Comment