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?
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?
Create a new object and use bracket notation to set the property.
function createObject(attr) {
var obj = {};
obj[attr] = "test";
return obj;
}
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);
This way?
createObject(attrName) {
var obj = {};
obj[attrName] = 'test';
return obj;
}