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

24 thoughts on “Node JS Nested Array Transformation”

  1. 319404 209056Does your site have a contact page? Im having trouble locating it but, Id like to send you an email. Ive got some suggestions for your blog you may be interested in hearing. Either way, fantastic blog and I appear forward to seeing it develop over time. 274408

    Reply

Leave a Comment