如何在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'}


谢谢

最佳答案

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;
}, {});

09-17 12:04