-
-
Save msalahz/4d1d9693c5bd35d75fe107ac442ded63 to your computer and use it in GitHub Desktop.
Array to Object Converter
This file contains 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
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])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment