Object Inject - Insert Item into Javascript Hash
Objects (or hash) in javascript is commonly considered an associative array. They can be a little trickier to deal with than normal array. Recently I needed to insert an item into an object at a very specific location, dependent on some logic. Well with an object it is a bit trickier than with an array where you might splice, join, etc.. Lets give an example. Suppose I have this array, and suppose they are in this particular order for a reason (maybe age, or number of toes):
var tmp1 = {
Tom: 'first',
Jane: 'second',
Sally: 'third',
Bill: 'forth',
Lydia: 'fifth',
Carl: 'sixth',
Stan: 'seventh',
Earl: 'eighth',
Paul: 'ninth',
Tray: 'tenth'
};
Now lets consider I need to insert myself into this object right before "Earl". The solution is this little function:
ObjectInject = function(object, newKey, newVal, fn, bind){
var prevKey=null, prevVal=null, inserted=false, newobject={};
for(var currKey in object){
if (object.hasOwnProperty(currKey)){
var currVal = object[currKey];
if( !inserted && fn.call(bind, prevKey, prevVal, currKey, currVal) ){
newobject[newKey] = newVal;
inserted=true;
}
newobject[currKey] = currVal;
prevKey = currKey;
prevVal = currVal;
}
}
if(!inserted) newobject[newKey] = newVal;
return newobject;
};
This function takes 5 parameters:
- object = the object to work on
- newKey = the new key to insert
- newVal = new value to insert
- fn = a function called per iteration, return true to insert at this position
function (previousKey, previousValue, nextKey, nextValue){ } - bind = (optional) the object to use as 'this' in the function.
To insert myself right before Earl, I would call it like this:
var tmp2 = ObjectInject(tmp1, 'Trent', 'NEW ITEM', function(pk, pv, nk, nv){
return (nk=='Earl');
});
/*
var tmp2 = {
Tom: 'first',
Jane: 'second',
Sally: 'third',
Bill: 'forth',
Lydia: 'fifth',
Carl: 'sixth',
Stan: 'seventh',
Trent: 'NEW ITEM',
Earl: 'eighth',
Paul: 'ninth',
Tray: 'tenth'
};
*/
I originally wrote this while using mootools, and created a pull request on Mootools-Core, however it was noted in the comments that this "ordering" of the keys in a javascript object is not exactly an ECMAScript standard. So play at you're own risk! The version I provided here however should be library independent, so it should play nicely with jQuery, Mootools, etc.. Enjoy!