I have a JSON object structured like this:
{
"id": 12,
"firstName": "Mohamed",
"lastName": "Sameer",
"contactgroups": [
{
"id": 16,
"group": {
"id": 4,
"groupname": "Angular"
}
},
{
"id": 19,
"group": {
"id": 5,
"groupname": "React"
}
},
{
"id": 20,
"group": {
"id": 6,
"groupname": "Node"
}
}
]
}
Desired output format:
{
"id": 12,
"firstName": "Mohamed",
"lastName": "Sameer",
"groups": [4, 5, 6] // retrieved from 'group' object with id and groupname //
}
I am looking to accomplish this using JavaScript methods without resorting to for loops.
Can it be achieved using the map method?
This was my attempt:
const data = {
"id": 12,
"firstName": "Mohamed",
"lastName": "Sameer",
"contactgroups": [
{
"id": 16,
"group": {
"id": 4,
"groupname": "Angular"
}
},
{
"id": 19,
"group": {
"id": 5,
"groupname": "React"
}
},
{
"id": 20,
"group": {
"id": 6,
"groupname": "Node"
}
}
]
}
const finalData = data.contactgroups.map(x => ({
id: data.id,
firstName: data.firstName,
lastName: data.lastName,
groups: [x.group.id]
}));
console.log(finalData);