在循环中创建命名的javascript对象 [英] Creating named javascript objects in loop

查看:105
本文介绍了在循环中创建命名的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;
}

这篇关于在循环中创建命名的javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆