Reputation: 1357
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
Please help me fix the dynamic object creation
Upvotes: 0
Views: 88
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
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
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