I’m looking for reduce elements of array to one object by same key (id).
I try to use Array.reduce
, but cannot reduce same id elements.
Actually I don’t really full understand Array.reduce
‘s mechanism… 🙁
Can anybody help me?
const arr = [{id: 1, value: 1, key: 'email'}, {id: 1, value: 1, key: 'status'}, {id: 2, value: 2, key: 'email'}, {id: 2, value: 2, key: 'status'}];
// EXPECTED
const arr = [{id: 1, data: {'email': 1, 'status': 1}}, {id: 2, data: {'email': 2, 'status': 2}}];
// WHAT I DO
const result = arr.reduce((acc, cur)=>{
const {id, key, value} = cur;
acc.forEach(el => {
if (el.id === id) {
el.data[key] = value;
}
})
acc = [...acc, {'id': id, 'data': { [key]: value }}];
return acc
}, [])
// WHAT I GET
[
{ id: 1, data: { email: 1, status: 1 } },
{ id: 1, data: { status: 1 } },
{ id: 2, data: { email: 2, status: 2 } },
{ id: 2, data: { status: 2 } }
]