Skip to content

Instantly share code, notes, and snippets.

@imparvez
Created March 5, 2018 07:33
Show Gist options
  • Save imparvez/7354d86022e9d084f16e22ad0db6b347 to your computer and use it in GitHub Desktop.
Save imparvez/7354d86022e9d084f16e22ad0db6b347 to your computer and use it in GitHub Desktop.
Array to Object Converter
var arr = ["a", "b", "c"];
var obj = {};
/* Method no: 1 */
arr.forEach(function(item, index) {
obj[index] = item;
});
console.log('Object is: ', obj);
/* Method no: 2 */
// Create a function where conversion of array to object is taking place.
function converter(arr) {
var newObj = {};
for(var i = 0; i < arr.length; i++) {
newObj[i] = arr[i];
}
return newObj;
}
console.log('New Object is: ', converter(arr));
/* Method no: 3 */
// Object.assign(): copy the values of all enumerable own properties from
// one or more source objects to a target object.
console.log('Fastest Object created is: ', Object.assign({}, arr));
/* Method no: 4 */
Array.prototype.toObject = function(key) {
var latestObj = {}; // creating an empty object
var temp = this;
if(key.length == temp.length) {
var count = temp.length - 1;
while(count >= 0) {
latestObj[key[count]] = temp[count];
count--;
}
}
return latestObj;
}
console.log('Object is: ', arr.toObject([1,2,3]));
@ppseprus
Copy link

ppseprus commented Mar 5, 2018

arr.reduce((obj, element, index) => {
  obj[index] = element;
  return obj;
}, {});

@imparvez
Copy link
Author

imparvez commented Mar 5, 2018

Hey thanks @ppseprus, I'll surely add this method in my list.

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