ES6 map an array of objects, to return an array of objects with new keys

JavascriptEcmascript 6

Javascript Problem Overview


I have an array of objects:

[
    {
        id: 1,
        name: 'bill'
    },
    {
        id: 2,
        name: 'ted'
    }
]

Looking for a simple one-liner to return:

[
    {
        value: 1,
        text: 'bill'
    },
    {
        value: 2,
        text: 'ted'
    }
]

So I can easily pump them into a react dropdown with the proper keys.

I feel like this simple solution should work, but I'm getting invalid syntax errors:

this.props.people.map(person => { value: person.id, text: person.name })

Javascript Solutions


Solution 1 - Javascript

You just need to wrap object in ()

var arr = [{
  id: 1,
  name: 'bill'
}, {
  id: 2,
  name: 'ted'
}]

var result = arr.map(person => ({ value: person.id, text: person.name }));
console.log(result)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen174View Question on Stackoverflow
Solution 1 - JavascriptNenad VracarView Answer on Stackoverflow