我有以下代码:
pub.call_response = function() {
return {
units: [
{
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
}
}
]
};
};
显然,这不起作用。有没有人对如何做这样的事情有任何想法?使用jQuery是可以接受的。
谢谢!
答案 0 :(得分:5)
你应该做
var key1 = something;
var key2 = something;
var value1 = something;
var value2 = something;
var attributes = {};
attributes[key1] = value1;
答案 1 :(得分:1)
要引用对象prop
上的属性obj
(即prop.obj
),您还可以使用方括号[]
因此,以下内容是等效的:
var x = prop.obj;
var key = "obj";
var t = prop[key];
答案 2 :(得分: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;
};
答案 3 :(得分: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
}]
};
};
答案 4 :(得分:-1)
var obj = {};
obj[key1] = value1;
obj[key2] = value2;
return {
units: [ { test_attributes: obj } ]
};