Ellone
Ellone

Reputation: 3898

Convert array into different structure using array values

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

Answers (2)

Microfed
Microfed

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

void
void

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

Live Fiddle

Upvotes: 3

Related Questions