[英]init javascript object with array property with child objects
Is there a way to initialize a javascript object with an array of child objects in one line? 有没有一种方法可以用一行中的一系列子对象来初始化javascript对象? How can I do the following in just on initialization line. 我如何仅在初始化行上执行以下操作。
var obj = {doc: 100,
defaultrateid: 32,
rates: [],
};
obj.rates[31] = {rate: 101.00, name: "Rate 1"};
obj.rates[32] = {rate: 121.00, name: "Rate 2"};
Basically what I want is a single javascript object that has my user parameters. 基本上我想要的是具有我的用户参数的单个javascript对象。 This object will be reused on multiple web forms. 该对象将在多个Web表单上重用。 In the case of 'rates', the forms will have a dropdown to select a rate. 在“费率”的情况下,表格将具有一个下拉列表以选择费率。 The web forms have client side calculations that require the matching rate object based on the rate's unique id (eg 32). Web表单具有客户端计算,这些计算需要基于比率的唯一ID(例如32)的比率对象。
I'm trying to use a associative array instead of having to do looping for finding a match based on unique value. 我正在尝试使用关联数组,而不必进行循环以基于唯一值查找匹配项。
Seems a bit hacky: 似乎有点hacky:
obj = {
doc: 100,
defaultrateid: 32,
rates: (new Array(30)).concat([{
rate: 101.00,
name: "Rate 1"
}, {
rate: 121.00,
name: "Rate 2"
}])
};
Maybe you don't really need an array, you can use an object like this: 也许您实际上并不需要数组,可以使用如下对象:
obj = {
doc: 100,
defaultrateid: 32,
rates: {
"31": {
rate: 101.00,
name: "Rate 1"
},
"32": {
rate: 121.00,
name: "Rate 2"
}
}
};
And you can still get the rates like obj.rates[31]
. 而且您仍然可以获得obj.rates[31]
类的价格。
Do you mean like this? 你是这个意思吗
var obj = { doc: 100, defaultrateid: 32, rates: [{ rate: 101.00 }, { rate: 121.00 }], }; alert(obj.rates[1].rate);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.