This allows you to generate from an array an object with keys you define in the order you want them.
Array.prototype.toObject = function(keys){
var obj = {};
var tmp = this; // we want the original array intact.
if(keys.length == this.length){
var c = this.length-1;
while( c>=0 ){
obj[ keys[ c ] ] = tmp[c];
c--;
}
}
return obj;
};
result = ["cheese","paint",14,8].toObject([0,"onion",4,99]);
console.log(">>> :" + result.onion); will output "paint", the function has to have arrays of equal length or you get an empty object.
Using
javascript#forEach
one can do thisWith ECMA6:
Or use
I have faced this issue multiple times and decided to write a function that is as generic as possible. Have a look and feel free to modify anything
Five years later, there's a good way :)
Object.assign
was introduced in ECMAScript 2015.This allows you to generate from an array an object with keys you define in the order you want them.
console.log(">>> :" + result.onion);
will output "paint", the function has to have arrays of equal length or you get an empty object.Here is an updated method
If you can use
Map
orObject.assign
, it's very easy.Create an array:
The below creates an object with index as keys:
Replicate the same as above with Maps
Converts to an index based object
{0 : 'css'}
etc...Convert to an value based object
{css : 'css is great'}
etc...