I'm looking to normalise some data returned from an API. Already using underscore within the project.
var res = [{
badge_no: 123,
id: 1,
name: 'bob'
}, {
badge_no: 456,
id: 2,
name: 'bill'
}, {
badge_no: 789,
id: 3,
name: 'ben'
},
// etc
];
I'm looking to create a data structure that looks like:
var normalisedRes = [{
1: {
badge_no: 123,
id: 1,
name: 'bob'
}
}, {
2: {
badge_no: 456,
id: 2,
name: 'bill'
}
}, {
3: {
badge_no: 789,
id: 3,
name: 'ben'
}
}];
It is important that I keep the id within the obj. I believe I can accomplish this with reduce
but I'm struggling.
Thanks for your help!
EDIT: This question has now been answered.
From some of the advice on here, I have decided to normalise the data to return an obj which looks like:
{ '1': {data}, '2':{data}, '3':{data} }
To do this I used reduce, as I originally thought I should:
var normalised = res.reduce((acc, person) => {
acc[person.id] = person;
return acc;
}, {});
Thanks again for all the answers!