简体   繁体   中英

get all values from javascript array

I have array like this:

a = [{"province":"Western"},{"province":"Central "},{"province":"Southern "}]

in 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 (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:

"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);

Demo

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM