1

I am creating an object in a function:

createObject(attr) {
    return {
        attr: "test"
    }
}

I want the attr to be named by the function parameter. Right now I end up with this object:

{
    attr: "test"
}

How do I do this?

jhamm
  • 24,124
  • 39
  • 105
  • 179
  • square-bracket notation – ddavison Aug 19 '15 at 17:23
  • 1
    possible duplicate of [this](http://stackoverflow.com/questions/2462800/how-to-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable) and [this](https://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – ddavison Aug 19 '15 at 17:23

3 Answers3

4

Create a new object and use bracket notation to set the property.

function createObject(attr) {
    var obj = {};
    obj[attr] = "test";
    return obj;
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
2

I made this pen to show you how to construct the object:

http://codepen.io/dieggger/pen/pJXJex

//function receiving the poarameter to construct the object
var createObject = function(attr) {
  //custom object with one predefined value.
   var myCustomObject = {
    anything: "myAnything",
  };

 //adding property to the object 
  myCustomObject[attr] = "Test";

 //returning the constructed object
  return myCustomObject;

}

//invoking function and assigning the returned object to a variable
var objReturned = createObject("name");

//simple alert , to test if it worked
alert(objReturned.name);
Diego Montes
  • 43
  • 1
  • 6
0

This way?

createObject(attrName) {
    var obj = {};
    obj[attrName] = 'test';
    return obj;
}
pesho hristov
  • 1,946
  • 1
  • 25
  • 43