stewart715
stewart715

Reputation: 5647

javascript using variables for object keys and values

I have the following code:

 pub.call_response = function() {
            return {
                units: [
                    {
                        test_attributes: {

                        }

                    }
                ]
            };
        };

I have a set of variables that I need to use for the keys/values in test_attributes as follows:

var key1 = something;
var key2 = something;
var value1 = something;
var value2 = something;

pub.call_response = function() {
                return {
                    units: [
                        {
                            test_attributes: {
                               key1: value1,
                               key2: value2
                            }

                        }
                    ]
                };
            };

Obviously, this does not work. Does anyone have any ideas on how to do something like this? Using jQuery is acceptable.

Thanks!

Upvotes: 3

Views: 10654

Answers (5)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34591

var obj = {};
obj[key1] = value1;
obj[key2] = value2;

return {
    units: [ { test_attributes: obj } ]
};

Upvotes: -1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You should do

var key1 = something;
var key2 = something;
var value1 = something;
var value2 = something;

var attributes = {};

attributes[key1] = value1;

Upvotes: 8

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

var key1 = something;
var key2 = something;
var value1 = something;
var value2 = something;

pub.call_response = function() {
    var u    = {};
    u[key1]  = value1;
    u[key2]  = value2;

    return {
         units: [{
             test_attributes : u
         }]
    };
};

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

var key1 = something;
var key2 = something;
var value1 = something;
var value2 = something;

pub.call_response = function() {
    var item = {
        test_attributes: {}
    };
    item.test_attributes[key1] = value1;
    item.test_attributes[key2] = value2;

    var obj = {
        units: [item]
    };

    return obj;
};

Upvotes: 1

Mutation Person
Mutation Person

Reputation: 30498

To reference the property prop on the object obj (i.e. prop.obj) you can also use the square brackets []

So, the following are equivalent:

var x = prop.obj;

var key = "obj";
var t = prop[key];

Upvotes: 1

Related Questions