Patrick
Patrick

Reputation: 4298

convert array into an array of ojects

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

Answers (4)

user3335966
user3335966

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

brk
brk

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)

JSFIDDLE

Upvotes: 1

David H.
David H.

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

tymeJV
tymeJV

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

Related Questions