Last active
June 12, 2018 17:02
-
-
Save vaderj/b4a328375349af81b44c83712695cc20 to your computer and use it in GitHub Desktop.
JS - Array to Object #Javascript
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
//From https://stackoverflow.com/questions/4215737/convert-array-to-object | |
//Given the following array: | |
var testArray = ["a","b","c","d"] | |
//Simplest data transformation method: | |
function toObject(arr) { | |
var rv = {}; | |
for (var i = 0; i < arr.length; ++i) | |
rv[i] = arr[i]; | |
return rv; | |
} | |
//Method which has built-in "hole" removal (tests for invalid values in the array) | |
function toObject(arr) { | |
var rv = {}; | |
for (var i = 0; i < arr.length; ++i) | |
if (arr[i] !== undefined) rv[i] = arr[i]; | |
return rv; | |
} | |
//Alternativly using Array.reduce method on instanciation, invalid values may be trimmed like this: | |
var obj = arr.reduce(function(acc, cur, i) { | |
acc[i] = cur; | |
return acc; | |
}, {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment