This is another tiny helper I’ve just realized I need badly. I often do something like this to convert Arrays holding Objects into Objects holding Objects for easier lookups:

var newObject = {};
for (var i=0; i < someArray.length; i++) {
	newObject[someArray[i].id] = data[i];
};

I realized this can be beautified a bit by creating Array.toObject:

Array.prototype.toObject = function(f) {
	var o = {};
	for(var i=0; i < this.length; i++) {
		o[f.call(this[i])] = this[i];
	}
	return o;
};

This very simple function lets you transform the above code to

var newObject = someArray.toObject(function() {
	return this['id'];
});

Arguably it is not much shorter, but simpler. The anonymous function is needed because we need to tell the toObject function how to build up the Object key for each Array entry. Cool enough, this doesn't only work with Objects now, but with any kind of Array data. If in fact we know we're only dealing with Arrays holding offsets, we can optimize:

Array.prototype.toObject = function(key) {
	var o = {};
	for(var i=0; i < this.length; i++) {
		o[this[i][key]] = this[i];
	}
	return o;
};

..which then lets us do:

var newObject = someArray.toObject('id');

Now that's better, no? Enjoy :)







2 Comments

Tech Thursday – Python and YQL, new Google layout, Quake in Flash and LOLSQL | Techno Portal  on November 26th, 2009

[…] Paul Bakaus of the jQuery team has a nice small solution to turn arrays into objects in JavaScript. […]

Radoslav Stankov  on November 27th, 2009

Nice, PrototypeJs have something similar – Enumerable.pluck / http://api.prototypejs.org/language/enumerable.html#pluck-instance_method /

But your idea with the function is nice. You may check the argument type if it is function to call it, if it is string to pluck it. if no argument is given just an object with 0/1/2/3…

Have a comment or question?