Home > front end >  TypeScript: Combine objects of an array to make a specific JSON
TypeScript: Combine objects of an array to make a specific JSON

Time:05-20

I am looping through an array of objects and I am trying to combine them to a specific JSON:

The array of objects:

[
    {
    'code': 'LA',
    'name': 'Local administrator',
    'id': 1
    },
    
    {
    'code': 'SA',
    'name': 'System administrator',
    'id': 2
    }
]

How can I combine them and have something like this?

[
   {
      "role":{
         "code":"LA",
         "name":"Local administrator",
         "id":1
      }
   },
   {
      "role":{
         "code":"SA",
         "name":"System administrator",
         "id":2
      }
   }
]

I am trying here if you like to help please fork this: https://www.typescriptlang.org/play?ts=4.6.2&ssl=41&ssc=2&pln=26&pc=1#code/AQGwpgLsCGBOvQJ7ALzANoG8CwAoYBA5AMYD2AJmIQFzCEAyAgoQDR4F0B20AtlbQ1LFoIGOR4BLThIDOEBBFKxW7IhPI1gARnYBfFsBz4iZSpsIBlZm2Nde-OhcRywPMZOlyFSlbcLrNACY9AF0Abjx2cCgIVwAHC2gANzBGeCRaaE5kNExdCPxo4FieOIAlUnAZTOzUDHDI-DgERAA6ADMlAFFoYgALAApyaAhoVAA Q1Vi IqquvRWpZLyyrAZA2HRhvxdAEoC9hXElLSW9EJYNcIQuqMOJdaVufW9AuAyThk11pBSAHMBsdkql0ogDo0APQAKmAfVIAHcPllgABJYD-SDFPpgYCdEB-BFSf7AWDrACuIAgAH5gNDIXgYY10NN7hwCAAiK7gDnUNnsjgc0xgXkcpgcmwC9kc7h8UX0IQidxSWTyEZKCXTKUc9S8nS2Di6ab6VlaznckV8s3S4Wiqyag0CmX2O3OErKzxqxSwB1SwW66jBR3AI22UMhRr0oA

CodePudding user response:

Map over each array, returning a new object for each element:

array.map((role) => ({ role }));

({ role }) is short for ({ role: role }). There are parentheses so that the object literal is not confused for the body of the arrow function.

let array = [{
   'code': 'LA',
   'name': 'Local administrator',
   'id': 1
 }, {
   'code': 'SA',
   'name': 'System administrator',
   'id': 2
 }];

console.log(array.map((role) => ({ role })));

  • Related