0

I have an array of values in state as

constructor {
    super(props);
    this.state = {
        staff: {
                pos1: { name:'Ajith'}
                pos2: { name:'Ben'}
              }
    }
}
componentDidMount() {
    this.state.staff.map((item,index) => {
        console.log(item+" * "+index)
    }
}

I got an error this.state.staff.map is not a function as the index is not as 0, 1 etc. How can I fix this?

2
  • Because this.state.staff is not an array !!. It's an object Commented Jun 4, 2018 at 6:19
  • Possible duplicate of loop on object Commented Jun 4, 2018 at 7:56

2 Answers 2

0

Few things to be noted here based on your question,

Staff is not an array so you wont be able use map, in order for you to use map you will need to object.keys.

Also you are missing a comma in the staff value section.

       staff:  {
            pos1: { name:'Ajith'},
            pos2: { name:'Ben'}
          }

To use map:

  Object.keys(staff).map((data) => staff[data].name )

It will return the output as:

["Ajith", "Ben"]
Sign up to request clarification or add additional context in comments.

Comments

0

cause staff is an Object not a Array, so you can't map staff. But you can try this

Object.key(this.state.staff).map((key, index) => { const item = this.state.staff[key] console.log(item+" * "+index) })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.