Skip to content

Instantly share code, notes, and snippets.

@freidamachoi
Created May 30, 2013 16:33
Show Gist options
  • Save freidamachoi/5679259 to your computer and use it in GitHub Desktop.
Save freidamachoi/5679259 to your computer and use it in GitHub Desktop.
/*
Javascripters can create inline object literals with dynamic values:
var sue = {name: "Sue", adult: person.age >= 18};
Javascripters cannot create inline object literals with dynamic keys:
var family = {herman.role: herman, lily.role: lily} //impossible...
// family == {husband: herman, wife: lily};
var family = {}; //...unless we resort to longhand.
family[herman.role] = herman;
family[lily.role ] = lily;
But I prefer shorthand:
var family = _.roll(herman.role, herman, lily.role, lily) //possible
*/
_.mixin({
//rolls an array of key/value pairs into an object
roll: function(){
var args = _.toArray(arguments);
if (args.length == 1) {
var firstItem = _.first(args);
if (_.isArray(firstItem)){
args = firstItem;
} else {
return firstItem;
}
}
var object = {};
for(var idx = 0; idx < args.length; idx += 2){
var key = args[idx], value = args[idx + 1];
object[key] = value;
}
return object;
},
//unrolls an object into an array of key/value pairs
unroll: function(object){
var array = [];
_.each(object, function(value, key){
array.push(key); array.push(value);
});
return array;
}
});
_.mixin({toObject: _.prototype.roll}); //a possible alias
//Example:
var stooge = {
name: "Moe",
occupation: ["actor", "comedian"],
birthday: "June 19",
age: 77
};
var array = _.unroll(stooge);
var object = _.roll(array);
var moe = _.unroll(object);
console.log({
stooge: stooge,
array : array,
object: object,
moe : moe,
alikeObjects: _.isEqual(stooge, object),
alikeArrays : _.isEqual(moe, array)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment