在循环中创建命名的javascript对象
我正在寻找这种类型的javascript对象的解释:
I am looking for an explanation how this type of javascript object:
var regions = {
'Belgium': { tooltip: 'Test', attr: { fill: '#ff0000' } },
'Netherlands': { tooltip: 'Test', attr: { fill: '#ff0000' } },
'USA': { tooltip: 'Test', attr: { fill: '#ff0000' } },
'United_Kingdom': { tooltip: 'Test', attr: { fill: '#ff0000' } },
'Tanzania': { tooltip: 'Test', attr: { fill: '#ff0000' } },
'Germany': { tooltip: 'Test', attr: { fill: '#ff0000' } },
'France': { tooltip: 'Test', attr: { fill: '#ff0000' } },
'Spain': { tooltip: 'Test', attr: { fill: '#ff0000' } }
};
可以在浏览器中生成这个,以及我如何以编程方式创建这样的对象:
can result into this in the browser and how I can programatically create such object:
Netherlands: Object,
United_Kingdom: Object,
> Tanzania: Object…
> attr: Object
fill: "#00ff11"
tooltip: "Test"
> Australia: Object...
> attr: Object
fill: "#00ff11"
tooltip: "Test"
我在这里想要实现的是在浏览器中获得相同的结果,但是具有动态的对象列表(因此没有声明性代码而不是上面的区域对象)。
What I'm trying to achieve here is to have the same result in the browser but with a dynamic list of objects (so no declarative code as opposed to the regions object above).
目前我使用的方法是结果是一个字符串,这不是我需要的。此外,它是非常难看的代码,我想摆脱:
For the moment I use this method but the result is a string, which is not what I need. Besides, it's really ugly code which I'd like to get rid of:
function getRegions(data) {
var arr = new Array();
$.each(data, function (i, country) {
var row = "'" + data[i].Country + "': { tooltip: 'Test', attr: { fill: '" + data[i].Color + "'} }";
var parsedJson = JSON.parse(JSON.stringify(row));
arr.push(parsedJson);
});
var result = JSON.parse(JSON.stringify('{ ' + arr + '}'));
return result;
}
我无法理解如何实例化命名对象以及如何我可以在循环中以编程方式执行此操作,而无需事先知道实际名称。我需要一些像这样的结构,但我怀疑这实际上会有效:
I'm having problems to understand how the named objects are being instantiated and how I can do this programmatically in a loop without knowing the actual names upfront. I'd need some constructions like this but I doubt that this will actually work:
var data[i].Country = { tooltip: 'Test', attr: { fill: '#ff0000' } };
任何想法如何解决这个问题?
Any ideas how to solve this?
你已经过时了。您可以使用对象文字符号和括号表示法。
You are way over complicating this. You can just use object literal notation and bracket notation.
function getRegions(data) {
var result = {};
$.each(data, function (i, country) {
result[data[i].Country] = {
tooltip: 'Test',
attr: {
fill: data[i].Color
}
};
});
return result;
}