hbulens
hbulens

Reputation: 1969

Creating named javascript objects in loop

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?

Upvotes: 0

Views: 466

Answers (1)

Lenny
Lenny

Reputation: 5939

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

Upvotes: 3

Related Questions