Jason Yan
Jason Yan

Reputation: 3

how to return an object in a map function (React.js)

I have some user input, I need to split them into characters, then just using map to return both the character array and index array as an object. Try many ways but all failed. Hope I can get some helps here. I am new to react.js and my code may sounds dum. The code is in App.js the main component.

  charList = () => { 
    this.state.userInputs.split("").map((ch1, index1) => 
    { return {ch: ch1, index: index1}
    } ); 
  }

I want to be able to access this.charList.ch and this.charList.index for the two arrays. Not sure I described my question clearly. Thanks in advance.

Upvotes: 0

Views: 6188

Answers (2)

sidverma
sidverma

Reputation: 1185

try this :

 return  this.state.userInputs.split("").map((ch1, index1) => 
        { 
            let obj= {};
            obj.ch = ch1; 
            obj.index = index; 
         return obj;
        }); 

Upvotes: 0

Ross Mackay
Ross Mackay

Reputation: 972

If you want something like this:

[
  { "ch": "h", "index": 0 },
  { "ch": "i", "index": 1 }
]

You're just missing a return before this.state.userInputs.split("")

charList = () => { 
    return this.state.userInputs.split("").map((ch1, index1) => {
        return {ch: ch1, index: index1 }
    })
}

Upvotes: 1

Related Questions