ES6 map an array of objects, to return an array of objects with new keys [duplicate]
Asked Answered
S

1

317

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 })
Sticky answered 31/10, 2016 at 18:21 Comment(1)
You need person => ({.... In other words, enclose the object literal in parens. Otherwise JS thinks it's the beginning of a block.Gearhart
S
742

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)
Silverpoint answered 31/10, 2016 at 18:23 Comment(6)
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.Sticky
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.Sticky
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 }; });Misdirect
If don't want to add the parenthesis then instead of ":" use "=". this.props.people.map(person => { value= person.id, text= person.name })Doubledealing
@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.Misspend
can we make the key to be dynamic here ? for e.g some property from inside PersonEstey

© 2022 - 2024 — McMap. All rights reserved.