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?

2
  • square-bracket notation Commented Aug 19, 2015 at 17:23
  • 1
    possible duplicate of this and this Commented Aug 19, 2015 at 17:23

3 Answers 3

4

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

function createObject(attr) {
    var obj = {};
    obj[attr] = "test";
    return obj;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

This way?

createObject(attrName) {
    var obj = {};
    obj[attrName] = 'test';
    return obj;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.