const array = [{
"id": "1",
"main": [{
"type": "a",
"nu": '0',
"role": 1
}],
}, {
"id": "2",
"main": [{
"type": "b",
"nu": '0',
"role": 2
}],
}, {
"id": "3",
"main": [{
"type": "c",
"nu": '0',
"role": 2
}],
}, {
"id": "4",
"main": [{
"type": "d",
"nu": '0',
"role": 2
}],
}]
From above object, i want to combine id- 2,3 and 4 into one key which has 3 objects.
const result = [array.reduce((acc, {id, main}) => {
const { nu, role, type } = main[0]
const hash = `${nu}-${role}`;
acc[hash] = acc[hash] ? [{ ...acc[hash] }, {type: type, id: id }] :
{ type, id: [id] };
return acc;
}, {})];
Expected:
Example:
const array = [{
"id": "1",
"main": [{
"type": "a",
"nu": '0',
"role": 1
}],
}, {
"id": "2",
"main": [{
"type": "b",
"nu": '0',
"role": 2
}],
}, {
"id": "3",
"main": [{
"type": "c",
"nu": '0',
"role": 2
}],
}, {
"id": "4",
"main": [{
"type": "d",
"nu": '0',
"role": 2
}],
}]
const result = [array.reduce((acc, {id, main}) => {
const { nu, role, type } = main[0]
const hash = `${nu}-${role}`;
acc[hash] = acc[hash] ? [{ ...acc[hash] }, {type: type, id: id }] :
{ type, id: [id] };
return acc;
}, {})];
console.log(result);
I am not sure where i am going wrong, can someone please help ?