I need a method to transform an array of JavaScript objects into an associative array using a specific attribute as the key.
For instance, if we have this array:
var data = [
{'id': 100, name: 'bob', foo: 'bar'},
{'id': 200, name: 'john', foo: 'qux'}
];
I want to access each object by its id, so the desired output is:
var new_data = {
100: {name: 'bob', foo: 'bar'},
200: {name: 'john', foo: 'qux'}
}
// now I can use new_data[200] to get 'john'
Although creating a new object and iterating over each original object to add a new key:value pair works, I'm curious if there's a more efficient way to achieve this.