简体   繁体   English

javascript使用变量作为对象键和值

[英]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: 我有一组需要用于test_attributes的键/值的test_attributes ,如下所示:

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. 可以使用jQuery。

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 [] 要引用对象obj上的属性prop (即prop.obj ),也可以使用方括号[]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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