2

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)}
]
2
  • 1
    That's not a JSON array. Do you simply mean an array in Javascript? Commented Dec 18, 2015 at 11:19
  • I meant object array I guess if JSON array is incorrect to qualify it. Commented Dec 18, 2015 at 11:39

2 Answers 2

10

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

Comments

3
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

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.