surj
surj

Reputation: 4903

Is there a way to create an object and assign it a dynamic property simultaneously?

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;

Upvotes: 3

Views: 89

Answers (4)

Travis J
Travis J

Reputation: 82287

jsFiddle Demo

You are looking for Object.defineProperty MDN method. You can define a new object and the assign the dynamic property using it.

function test(){
 var foo = "lol";
 return Object.defineProperty({},foo,{value:"bar"});    
}

alert(test().lol);

Upvotes: 1

surj
surj

Reputation: 4903

Not a huge fan of function-based answers, I'd rather have some kind of expression.

I came up with more compact form:

var obj, foo = "lol";
return ((obj = {})[foo] = "bar") && obj;

It would be cool if I could have the var obj inside the expression. Not sure how. It would be ultimate if I didn't have to define the obj variable.

Upvotes: 0

SergeyKutsko
SergeyKutsko

Reputation: 697

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}

Upvotes: 1

DougM
DougM

Reputation: 2888

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};

Upvotes: 1

Related Questions