[英]get all values from javascript array
I have array like this: 我有这样的数组:
a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}]
in javascript. 在javascript中。 I want to extract all province and put it as in data as mentioned below.
我想提取所有省份并将其放入如下所述的数据中。
data: [{id: 'province1', text: 'province1'},{id: 'province2', text: 'province2'},
{id: 'province3', text: 'province3'}]
I tried it with for loop. 我尝试了for循环。
for (index = 0; index < a.length; ++index) {
console.log(a[index]);
}
But, it's giving me character values.. 但是,这给了我角色价值。
You can build the ids by concatenating a string with a numeric id: 您可以通过将字符串与数字ID串联来构建ID:
"province" + index // "province1"
Summing up 加起来
var data = [];
for (index = 0; index < a.length; ++index) {
data[index] = { id: 'province' + (index+1), text: a[index].province} ;
}
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);
Result is 结果是
{Southern : "Southern ", Central : "Central ", Western: "Western"}
Edit as per the comment: 根据评论进行编辑:
var a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}];
a = a.map(function(v){
return { id : v.province, text : v.province };
});
console.log(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.