如何在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);
}
-------------------编辑--------------------
我希望新格式colorData
采用以下格式: -
{'CA': '#61c419', 'AZ':'#61c419'}
由于
答案 0 :(得分:2)
Array.prototype.map() 是您的朋友:
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;
});
如果您希望结果为{CA: '#61c419', AZ: '#61c419'}
,则:
var colorData = stateData.states.reduce(function(v, w) {
v[w.state] = w.color;
return v;
}, {});
答案 1 :(得分:1)
很容易尝试这个
<强> Working Demo 强>
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));
<强>输出强>
{"CA":"#61c419","AZ":"#61c419"}
答案 2 :(得分:0)
只需将项目分配给对象属性即可。 .push()
用于数组。
var o = {};
o.newProperty = 'hier';
o.otherProperty = [1, 2, 3];
答案 3 :(得分:0)
也许数组更适合:
...
var colorData = new Array();
...