Sam Hanson
Sam Hanson

Reputation: 1357

jquery create object dynamic not working

I need the output as

{       'US-CA': '#084365',
        'US-TX': '#084365',
        'US-CO': '#00a2e8',
        'US-NM': '#00a2e8',
        'US-WY': '#00a2e8',
        'US-NE': '#00a2e8'
    }

For this I used the following code:

   var output = [];

$('.vectordata').find('.varc').each(function(i){
            var t = $(this);
            regioncode = t.find('.regioncode').val();
            color = t.find('.color').val();
                    var obj2 = {}
                    obj2[regioncode] = color;
                    output.push(obj2);

    }

But the output I received is

enter image description here

Please help me fix the dynamic object creation

Upvotes: 0

Views: 88

Answers (3)

Rashedul.Rubel
Rashedul.Rubel

Reputation: 3584

You want to get output as JSON object like below:

{       'US-CA': '#084365',
        'US-TX': '#084365',
        'US-CO': '#00a2e8',
        'US-NM': '#00a2e8',
        'US-WY': '#00a2e8',
        'US-NE': '#00a2e8'
}

so, in order to serve your purpose you need to declare an object and put the values into object as {key:value} pair. Don't need any array to store the object again. You can follow samuellawrentz answer.

Upvotes: 2

Amit Wagner
Amit Wagner

Reputation: 3264

you dont need the array just put it in the object

 var output = {};

$('.vectordata').find('.varc').each(function(i){
            var t = $(this);
            regioncode = t.find('.regioncode').val();
            color = t.find('.color').val();
            output[regioncode] = color;
                   

    }

Upvotes: 2

samuellawrentz
samuellawrentz

Reputation: 1732

       var output = {};

    $('.vectordata').find('.varc').each(function(i){
                var t = $(this);
                regioncode = t.find('.regioncode').val();
                color = t.find('.color').val();
                        output[regioncode] = color;

        }

console.log(output);

You were pushing objects into Array. Make output as object.

Upvotes: 1

Related Questions