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