0

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

1
  • You are getting array of objects in output but you need literal object. This is because you are pushing single object in one array Commented Jul 18, 2018 at 5:53

3 Answers 3

2

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;
                   

    }

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1
       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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.