Skip to content

Instantly share code, notes, and snippets.

@killinit
Forked from Daniel-Hug/array-to-object.js
Created April 13, 2018 06:28
Show Gist options
  • Select an option

  • Save killinit/645a24066125a9c0c3a47342975b6b7b to your computer and use it in GitHub Desktop.

Select an option

Save killinit/645a24066125a9c0c3a47342975b6b7b to your computer and use it in GitHub Desktop.
JS arrayToObj(): convert array to object with a key-value map function
// 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;
}
@killinit
Copy link
Author

killinit commented Apr 13, 2018

function arrayToObj (array, fn) {
    var obj = {};
    var len = array.length;
    for (var i = 0; i < len; i++) {
        var item = fn(array[i], i, array);
        obj[item.key] = item.value;
    }
    return obj;
};

//calling example:

var arrayOfObjects=[{name:'banana',color:'yellow'},{name:'apple',color:'green'}];
var objectMap = arrayToObj(arrayOfObjects,function (item) {
                           return {key:item.name,value:item.color};
                        });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment