Umbro
Umbro

Reputation: 2204

How get to a nested array in object in react?

From the array based on the index, I choose a specific element. Assigns to the todo variable. I check in console.log todo. It is object. Inside this object is an array. I try to iterate this array, but he returns me body is not defined

class Todo extends Component {
  render () {
    let todo = this.props.todos[this.props.index]
    console.log(todo);

    return (
        <ul>
            { 
              todo.messages.map((obj, i) => {
                <li>{obj["body"]}</li>
              });   
            }
        </ul>
    )
  } 
}

export default Todo;

Console.log:

Object
  id: 1
  color: "sdsdsd"
  messages: (2) [{'body':'sdsdsd', 'title':'678'}, {'body':'aaaaaa'}, 
    'title':'11111'],
  title: "fgfgfgg"

Upvotes: 0

Views: 131

Answers (2)

Jordan Enev
Jordan Enev

Reputation: 18674

Your code's fine, except you have to return the result of the map function return <li>{obj["body"]}</li>.

Having such an error/warning body is not defined, it means some of your todo items, doesn't have a body property. Make sure all of your todos have a body property, or if the body isn't required, then conditionally render it.

Upvotes: 2

banerjeesouvik
banerjeesouvik

Reputation: 212

In that object that you consoled messages is not proper. I mean to say that the last element of messages is not in proper format. It is not an object.

Upvotes: 0

Related Questions