0

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.

4 Answers 4

7

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 }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

1

Underscore way (for old browsers without Array.map support):

var res = _.map(data, function(p, i){
    return {id: i + 1, label: p};
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.