Skip to content

Instantly share code, notes, and snippets.

@Angelfire
Last active January 14, 2016 14:20
Show Gist options
  • Save Angelfire/6086965456cede43689a to your computer and use it in GitHub Desktop.
Save Angelfire/6086965456cede43689a to your computer and use it in GitHub Desktop.
Map array data
/*
Create a mapped object by any identifier
example:
var a = [{id:1, name:'a'},{id:2, name:'b'},{id:3, name:'c'}];
a.mapBy('id')
output: [
{1:{id:1,name:'a'}},
{2:{id:2,name:'b'}},
{3:{id:3,name:'c'}}
]
a.mapBy('id', true)
output: [
{1:{name:'a'}},
{2:{name:'b'}},
{3:{name:'c'}}
]
*/
var a = [
{
"id": "PROMO255-4",
"programId": "1",
"name": "Promo cardSet # 255-4",
"cardQuantity": 450,
"loadedCards": [
{"quantity": 10, "amount": 55},
{"quantity": 20, "amount": 100}
]
},
{
"id": "PROMO257-2",
"programId": "1",
"name": "Promo cardSet # 257-1",
"cardQuantity": 67,
"loadedCards": [
{"quantity": 40, "amount": 25},
{"quantity": 18, "amount": 85},
{"quantity": 5, "amount": 50}
]
}
];
Array.prototype.mapBy = function (id, arr) {
var b = arr.reduce(function(map, obj){
map[obj[id]] = obj;
return map;
},{});
return b;
};
console.log(a.mapBy('id', a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment