Reputation: 4298
I have the following array list.
var data = [ "USA", "Denmark", "London"];
I need to convert it in this form
var data = [
{ "id" : 1, "label": "USA" },
{ "id" : 2, "label": "Denmark" },
{ "id" : 3, "label": "London" }
];
Can anyone please let me know how to achieve this.
Upvotes: 0
Views: 60
Reputation: 2745
Underscore
way (for old browsers without Array.map
support):
var res = _.map(data, function(p, i){
return {id: i + 1, label: p};
});
Upvotes: 1
Reputation: 50326
You can use forEach
to loop through the data array
var data = [ "USA", "Denmark", "London"];
var demArray =[];
data.forEach(function(item,index){
demArray.push({
id:index+1,
label:item
})
})
console.log(demArray)
Upvotes: 1
Reputation: 507
Simple version:
var convertedData = []
for (var i in data){
convertedData.push({id: i+1, label: data[i]});
}
data = convertedData; //if you want to overwrite data variable
Upvotes: 1
Reputation: 104785
Pretty easy using Array.map
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
var formatted = data.map(function(country, index) {
return { id: (index + 1), label: country }
});
Upvotes: 7