3

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!

0

5 Answers 5

8

You should do

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

var attributes = {};

attributes[key1] = value1;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1
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;
};

Comments

0
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
         }]
    };
};

Comments

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

return {
    units: [ { test_attributes: 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.