indra257 indra257 - 18 days ago 6
Javascript Question

mapping Json to form an array

Below is my Json

"Issues": [
{
"Id": null,
"Key": "Project20",
"Values": [
{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": "Project30",
"Values": [
{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]


I need to map this Json to form the below array

{ "Display Name": 'Rya', "UserName" : "RH", value: 350, url: "Project20" },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90, url:"Project30" }


Basically, I need to get the Key also in my array.

I tried

Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (acc[Key] = Value, acc), {}));


this gives me

{ "Display Name": 'Rya', "UserName" : "RH", value: 350 },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90 }


But I need the Key field also in the array

Answer

Use the initial value argument of reduce. So instead of {} pass { url: o.Key }:

Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (acc[Key] = Value, acc),
                                { url: o.Key }));