Skip to content

Instantly share code, notes, and snippets.

@vaderj
Last active June 12, 2018 17:02
Show Gist options
  • Save vaderj/b4a328375349af81b44c83712695cc20 to your computer and use it in GitHub Desktop.
Save vaderj/b4a328375349af81b44c83712695cc20 to your computer and use it in GitHub Desktop.
JS - Array to Object #Javascript
//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