Skip to content

Instantly share code, notes, and snippets.

@microbial
Last active August 29, 2015 14:13
Show Gist options
  • Save microbial/2555fc0a0666be4ef54c to your computer and use it in GitHub Desktop.
Save microbial/2555fc0a0666be4ef54c to your computer and use it in GitHub Desktop.
Array to Object Utility
//Makes array of objects into an object sorted by a requested key
//--> Key must be unique or collisions will happen and data lost
/** (v0.0.2) Works better!
-- softer failures (i.e. returns empty object instead of blowing up)
-- use key names from on inner levels (eg. name.first)
**/
function arrayToObject(keyToReplaceIndex, arr) {
var obj = {};
if(arr && arr.constructor === Array) {
arr.forEach(function(search, index) {
if(search) {
var currentItem;
keyToReplaceIndex.split('.').forEach(function(term) {
currentItem = currentItem ? currentItem[term] : search[term];
});
obj[currentItem] = arr[index];
}
});
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment