Dynamic object keys

Im trying to create an dynamic object with dynamic keys eg:

var test = "test";
var obj = {
    test:"bananas"
}

But I get an error: Uncaught SyntaxError: Unexpected token + Is this not allowed? anyway to do this? It's a must in my software.

Answers:

Answer
obj[test + "ing"] = "bananas";

In relation to your edit:

var test = "test";
var obj = {};
obj[test] = "bananas";

or shorter:

var obj={[test]:"bananas"};

I normally wrap this in something like:

Object.expander = function(name, value, obj)
{
    obj = obj || {};
    obj[name] = value;
    return obj;
};

var obj = Object.expander(test, "bananas");
Answer

you can't this way

try this instead

   obj["testing"] = "bananas"

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.