Reputation: 9748
How to insert an item in an object in Javascript
?
var colorData = new Object();
var stateData = {
states:
[
{ 'state' : 'CA', 'color' : '#61c419', 'amaguide' : '5'},
{ 'state' : 'AZ', 'color' : '#61c419', 'amaguide' : '5'}
]
}
for (var i = 0; i < stateData.length; i++) {
colorData.push(stateData[i].state + ':' + stateData[i].color);
}
-------------------edited--------------------
I want the new colorData
in the following format :-
{'CA': '#61c419', 'AZ':'#61c419'}
Thanks
Upvotes: 2
Views: 191
Reputation: 20751
Its very easy try this out
var colorData = new Object();
var stateData = {
states:
[
{ 'state' : 'CA', 'color' : '#61c419', 'amaguide' : '5'},
{ 'state' : 'AZ', 'color' : '#61c419', 'amaguide' : '5'}
]
};
for(var i=0; i<stateData.states.length; i++)
{
colorData[stateData.states[i].state] = stateData.states[i].color;
}
console.log(JSON.stringify(colorData));
Output
{"CA":"#61c419","AZ":"#61c419"}
Upvotes: 1
Reputation: 160893
Array.prototype.map() is your friend:
var stateData = {
states:
[
{ 'state' : 'CA', 'color' : '#61c419', 'amaguide' : '5'},
{ 'state' : 'AZ', 'color' : '#61c419', 'amaguide' : '5'}
]
};
var colorData = stateData.states.map(function(ele) {
return ele.state + ':' + ele.color;
});
If you want the result to be {CA: '#61c419', AZ: '#61c419'}
, then:
var colorData = stateData.states.reduce(function(v, w) {
v[w.state] = w.color;
return v;
}, {});
Upvotes: 2
Reputation: 339
Maybe a Array is better for that:
...
var colorData = new Array();
...
Upvotes: 0
Reputation: 2086
Simply assign the item to an object property. .push()
is for arrays.
var o = {};
o.newProperty = 'hier';
o.otherProperty = [1, 2, 3];
Upvotes: 0