我有这样的数组:
a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}]
在javascript中。我想提取所有省份并将其作为数据提供,如下所述。
data: [{id: 'province1', text: 'province1'},{id: 'province2', text: 'province2'},
{id: 'province3', text: 'province3'}]
我尝试了for循环。
for (index = 0; index < a.length; ++index) {
console.log(a[index]);
}
但是,它给了我个性价值..
答案 0 :(得分:3)
您可以通过将字符串与数字ID连接来构建ID:
"province" + index // "province1"
总结
var data = [];
for (index = 0; index < a.length; ++index) {
data[index] = { id: 'province' + (index+1), text: a[index].province} ;
}
答案 1 :(得分:1)
var a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}], b = {};
for(var i = a.length; i--; b[a[i].province] = a[i].province);
console.log(b);
结果是
{Southern : "Southern ", Central : "Central ", Western: "Western"}
根据评论进行编辑:
var a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}];
a = a.map(function(v){
return { id : v.province, text : v.province };
});
console.log(a);