Last active
August 29, 2015 14:13
-
-
Save microbial/2555fc0a0666be4ef54c to your computer and use it in GitHub Desktop.
Array to Object Utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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