Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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;
like image 939
surj Avatar asked Feb 01 '26 01:02

surj


2 Answers

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};
like image 116
DougM Avatar answered Feb 03 '26 14:02

DougM


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}
like image 37
SergeyKutsko Avatar answered Feb 03 '26 14:02

SergeyKutsko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!