304

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 })
Ben174
  • 3,654
  • 2
  • 17
  • 15
  • 50
    You need `person => ({...`. In other words, enclose the object literal in parens. Otherwise JS thinks it's the beginning of a block. –  Oct 31 '16 at 18:24

1 Answers1

717

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • 7
    Thanks! Not sure I understand why the parentheses are necessary, but they do indeed work. When using JSX, If I keep the tag on the same line, parentheses aren't required, so I guess I figured the same would be for an object on the same line. – Ben174 Oct 31 '16 at 18:25
  • 54
    Ah, from the post that this is apparently a duplicate of: "Otherwise curly braces will be considered to denote the function’s body." That makes sense now. Thanks again. – Ben174 Oct 31 '16 at 18:26
  • 2
    This will work too, but it is essentially just a different way to write the code, I added this because the OP did not understand the parenthesis, and I ran across this thread while solving an issue myself: var result = arr.map((person)=>{ return {value:person.id, text:person.name }; }); – ViaTech Feb 21 '18 at 23:55
  • 1
    If don't want to add the parenthesis then instead of ":" use "=". this.props.people.map(person => { value= person.id, text= person.name }) – Nitin Agarwal Oct 22 '18 at 08:19
  • 2
    @NitinAgarwal: Are you sure? Your suggestion does not work for me. And it makes sense, that it doesn't. I get an error saying that "value" and "text" are not declared. – Krisztián Balla Jan 16 '19 at 13:28
  • can we make the key to be dynamic here ? for e.g some property from inside Person – Harsh Gundecha Nov 25 '20 at 13:35