-
-
Save killinit/645a24066125a9c0c3a47342975b6b7b to your computer and use it in GitHub Desktop.
JS arrayToObj(): convert array to object with a key-value map function
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
| // Call arrayToObj() passing your array and function. | |
| function arrayToObj(array, keyValueMap) { | |
| var obj = {}; | |
| var len = array.length; | |
| // Your function will be called for each item in the array. | |
| for (var i = 0; i < len; i++) { | |
| var curVal = array[i]; | |
| // Just like with [].forEach(), your function will be passed the | |
| // curent item of the array, its index, and the array it's in. | |
| var keyValuePair = keyValueMap(curVal, i, array); | |
| // Your function should return a 2-value array with the key | |
| // and value for a new property in the object to be returned. | |
| obj[keyValuePair[0]] = keyValuePair[1]; | |
| } | |
| return obj; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//calling example: