我有一个像这样的javascript代码:
var myData=[];
$.getJSON( path_url , function(data){
var len = data.rows.length;
for (var i = 0; i < len; i++){
var code = data.rows[i].codeid;
var color = data.rows[i].color;
var obj = {}
obj[code] = color
myData.push(obj);
}
console.log(myData);
});
和结果
0: Object{12: "#fc0516"},1: Object{14: "#17a030"},2: Object{31: "#17a030"}
但结果我想这样:
{12:"#fc0516",14:"#17a030",31:"#17a030"}
如何获得上述结果?抱歉我的英语不好,提前谢谢...
答案 0 :(得分:3)
创建myData
作为对象,然后使用括号表示法分配属性值
var myData = {};
$.getJSON(path_url, function (data) {
var len = data.rows.length;
for (var i = 0; i < len; i++) {
var code = data.rows[i].codeid;
var color = data.rows[i].color;
myData[code] = color
}
console.log(myData);
});