Hello everyone, I'm new to this platform and seeking some advice. Can anyone help me with converting a JSON array to another JSON array while grouping by ID and including only the values of 'ID' and 'SID'? I've attempted using lodash and array.reduce but haven't been able to achieve the desired outcome. The input will consist of a large JSON array, so any tips on efficiently solving this problem would be greatly appreciated. Input:
[
{
"id": "11111",
"sid": "12345"
},
{
"id": "22222",
"sid": "23456"
},
{
"id": "22222",
"sid": "34567"
}
]
Expected Output:
[
{
"11111": [
"12345"
]
},
{
"22222": [
"23456",
"34567"
]
}
]
Lodash Method:
_.groupBy(array, x => x.id);
Output Using Lodash:
{
'11111': [
{ id: '11111', sid: '12345' }
],
'22222': [
{ id: '22222', sid: '23456' },
{ id: '22222', sid: '34567' }
]
}
Using Array Reduce Method:
const groupById = (array, key, value) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue[value]
);
return result;
}, {});
};
Output Using Array Reduce Method:
{
"11111": [
"12345"
],
"22222": [
"23456",
"34567"
]
}