0

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

2
  • So you just want to wrap the object in another object under a role property? Commented May 19, 2022 at 13:46
  • Yes and in fact there are more nested array of objects I would have to also found out how to add later. Commented May 19, 2022 at 13:53

1 Answer 1

1

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 })));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.