Ox Ox
Ox Ox

Reputation: 97

Get values from array of JSONs in JSON ReactJS

I'm trying to get values from JSON that looks like this:

{
    "id": 371,
    "city": "London",
    "name": "London Station",
    "trains": [
        {
            "id": 375,
            "number": "1023",
            "numberOfCarriages": "21"
        }
    ]
}

I want to get values from trains, like number and numberOfCarriages. I'm trying to get those values in React. My React code:

class ViewTrainsComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            id: this.props.match.params.id,
            station: []
        }
    }


    render() {
        return (
            <div>
                        <div className="row">
                            {/* <div>{this.state.station[0].trains[0].number}</div> */}
                        </div>
            </div>
        );
    }
}

Am I doing it right? How can I get those values in render function?

EDIT.

Here is the response from API enter image description here

Upvotes: 0

Views: 72

Answers (2)

sonali
sonali

Reputation: 758

Avoid setting and updating state directly with

this.state = ...

except when you are initializing it in the constructor. Instead, use either setState() function or the useState hook.

But I think your question is more about how to get the values of the trains in render function, You can access those as

render() {
    return <div>{this.state.stations[i].trains[j].number}</div>
  }

so for the first train of first station i=0 and j=0 and for the second train in first station i=0 and j=1. for the first train of second station i=1 and j=0 and for the second train in first station i=1 and j=1.

Upvotes: 1

Zac Anger
Zac Anger

Reputation: 7747

Assuming you have multiple of those JSON objects coming from somewhere (a file, an API request, whatever), you can do:

this.setState({ stations: yourParsedJson })

since the data and your proposed component state are the same shape.

Upvotes: 1

Related Questions