Reputation: 3898
Is there a simple way to get the latter array from the former?
Source array :
[1, 2, 3, 4, 5]
Target structure:
[
{id: 1, text: idToName(1)},
{id: 2, text: idToName(2)},
{id: 3, text: idToName(3)},
{id: 4, text: idToName(4)},
{id: 5, text: idToName(5)}
]
Upvotes: 2
Views: 242
Reputation: 2890
It's easy to use Array.prototype.map here:
var array = [1, 2, 3, 4, 5];
var mapped = array.map(function(num) { return { id: num, text: idToName(num) }; });
With ES6 arrow functions it would be:
let mapped = array.map(num => ({ id: num, text: idToName(num) }));
Upvotes: 10
Reputation: 36703
var _x = [1, 2, 3, 4, 5].map(function(v){
return {"id":v, "text":idToName(v)};
});
Use .map
, Live Fiddle
Or in ES6
var _x = [1, 2, 3, 4, 5].map(v => ({"id":v, "text":idToName(v)}));
Upvotes: 3