简体   繁体   中英

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!

You should do

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

var attributes = {};

attributes[key1] = value1;

To reference the property prop on the object obj (ie 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];
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;
};
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
         }]
    };
};
var obj = {};
obj[key1] = value1;
obj[key2] = value2;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM