0

I have an array of objects like so:

{
_id: "59d2a245734d1d42e49ed55d",
pollName: "Favourite Colour",
createdBy: "John",
pollData: [
    {key: "blue", value: 5},
    {key: "green", value: 7},
    {key: "red", value: 4},
    {key: "orange",value: 1}
    ]
},
{
_id: "59d2a291734d1d42e49ed574",
pollName: "Favourite Ice Cream",
createdBy: "Peter",
pollData: [
    {key: "Chocolate", value: 12},
    {key: "Vanilla", value: 7},
    {key: "Strawberry", value: 10}
    ]
}

I am trying to map these into Pie Charts but get syntax errors. This is the code in React:

render() {
    const {polls} = this.state

    return(

        <h1>Home</h1>

        {polls.map((poll, index) => (
            <div key={poll._id}>
                <Chart poll={poll} />
            </div>
        ))}

    )
}

The error message I get is on the opening brace:

Unexpected token, expected ,

{polls.map((poll, index) => (

I have done this previously on another project and it worked fine mapping through an array of objects, then passing each object into a component. Why is it not working in this instance?

3
  • 1
    wrap all the ui elements into a wrapper div, like this: return(<div><h1>.......</div>), we can't return more than one elements. Commented Oct 3, 2017 at 10:57
  • 1
    That did it - thank you @MayankShukla Commented Oct 3, 2017 at 11:08
  • @PramendraGupta it is an array of objects Commented Oct 3, 2017 at 11:09

2 Answers 2

0

There should be curly brackets istead of "( )"

    {polls.map((poll, index) => { 
     return <div key={poll._id}>
                <Chart poll={poll} />
            </div>  }
Sign up to request clarification or add additional context in comments.

2 Comments

curly braces with return or () are equivalent syntaxes. Problem is what mayank mentioned in his comment
I have tried it both ways with the same syntax error
0

const polls = [
  {
    _id: "59d2a245734d1d42e49ed55d",
    pollName: "Favourite Colour",
    createdBy: "John",
    pollData: [
      {key: "blue", value: 5},
      {key: "green", value: 7},
      {key: "red", value: 4},
      {key: "orange",value: 1}
    ]
  },
  {
    _id: "59d2a291734d1d42e49ed574",
    pollName: "Favourite Ice Cream",
    createdBy: "Peter",
    pollData: [
      {key: "Chocolate", value: 12},
      {key: "Vanilla", value: 7},
      {key: "Strawberry", value: 10}
    ]
  }
];


polls.map((poll, index) => {
  console.log(poll._id, poll.pollData)
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.