I'm a newbie here and would like some guidance. How do I convert the JSON array (input) to another JSON array but grouping by id and need just the values of 'id' and 'sid'.
I have tried using lodash, array.reduce but couldn't get the expected output.
The actual input will be a large JSON array and any suggestions on how to solve this efficiently will be much appreciated.
Input:
[
{
"id": "11111",
"sid": "12345"
},
{
"id": "22222",
"sid": "23456"
},
{
"id": "22222",
"sid": "34567"
}
]
Expected Output:
[
{
"11111": [
"12345"
]
},
{
"22222": [
"23456",
"34567"
]
}
]
lodash:
_.groupBy(array, x => x.id);
lodash output:
{
'11111': [
{ id: '11111', sid: '12345' }
],
'22222': [
{ id: '22222', sid: '23456' },
{ id: '22222', sid: '34567' }
]
}
array.reduce:
const groupById = (array, key, value) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue[value]
);
return result;
}, {});
};
array.reduce output:
{
"11111": [
"12345"
],
"22222": [
"23456",
"34567"
]
}