This might be a silly question, but I'm looking for a nice and compact way to both create an object, using the object literal notation, and assign it a dynamic property.
Right now, I'm doing it like this:
var foo = "lol";
var obj = {};
obj[foo] = "bar";
return obj;
// --> returns {lol:"bar"}
I'd like to do something like this:
var foo = "lol";
return ({}[foo] = "bar");
// --> returns {lol:"bar"}
Is there some kind of pattern to do this? I'm not too concerned about readability, although I'm looking for something compact if possible.
I can do it this way but it's pretty big, and pretty much exactly like splitting the statement into multiple lines.
var foo = "lol", obj;
return (obj = {}) && (obj[foo] = "bar") && obj;
Write a simple function that takes in name:value pairs as successive arguments, something like:
function dataBlob() {
var args = arguments;
for(var x = 0; x < arguments.length -1; x=x+2) {
this[args[x]] = args[x+1];
}
return this;
}
Which, assuming my JavaScript hasn't atrophied to the point the above is senseless, could be used as :
var obj = dataBlob("lol","bar", "lolz", 42);
which would be equivalent to the JSON-esque
var obj = {lol:"bar", lolz:42};
JSFidle Example
You can add this method to Object.prototype to get great functionality:
Object.prototype.push = function( key, value ){
this[ key ] = value;
return this;
}
var foo = "lol";
var obj = {};
obj.push(foo, "bar")
=>
Object {lol: "bar", push: function}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With