Search code examples
jsonangulartypescriptparsingtreetable

Parse JSON in TypeScript - add 'data' tag


Having a JSON that looks like this:

[  
   {  
      "id":1,
      "position":3,
      "articleNumber":"ServiceElement"
   },
   {  
      "id":2,
      "position":2,
      "articleNumber":"ServiceElement"
   }
]

Is it possible by any means to make it like:

{  
   "data":[  
      {  
         "data":{  
            "id":1,
            "position":3,
            "articleNumber":"ServiceElement"
         }
      },
      {  
         "data":{  
            "id":2,
            "position":2,
            "articleNumber":"ServiceElement"
         }
      }
   ]
}

I need that data tag to identify objects for a TreeTable implementation for which my given JSON is not conformed.


Solution

  • Just use map function to change item's shape.

    For first level we create a new object { data: } and then assign to data property the result of array.map.

    const array = [  
       {  
          "id":1,
          "position":3,
          "articleNumber":"ServiceElement"
       },
       {  
          "id":2,
          "position":2,
          "articleNumber":"ServiceElement"
       }
    ];
    
    const mapped = { data: array.map(item => ({ data: item }))};
    console.log(mapped);