I have an array of objects, for each element inside the array contains the same field as roleMapping
. I want to find all elements with the same key combined into an array. Below is the list of object array that I want to convert
a = [
{
roleMapping: {
123: {
shortName: "1",
name: "2"
},
234: {
shortName: "123",
name: "123"
},
}
},
{
roleMapping: {
123: {
shortName: "3",
name: "4"
}
}
},
{
roleMapping: {
234: {
shortName: "3",
name: "4"
}
}
}
]
I want to result:
a = {
123: [
{
shortName: "1",
name: "2"
},
{
shortName: "3",
name: "4"
}
],
234 : [
{
shortName: "123"
name: "123"
},
{
shortName: "3",
name: "4"
}
]
}
The purpose I use this is so that when I want to access the shortName
, I rely on the key of the object to find the value to use.
2
Answers
You can try with reduce
The function
convert
in the following code snippet does the required job: