0

The json data is a mixture of array and object. The object is well accessible. How do I access each of these data in an array? I think I can use map, but I get an error. I don't know how to pass values ​​using the map method. Please Help.

      <Query query={USER_QUERY}>
      {
        ({loading, error, data }) => {
          if (error) return 'error';
          if (loading) return 'loading';
          return (data.getUsers.history.dateInformation.map(data => (
            <Fragment>
              <p>User adid: </p>
              {data.monthly.month} 
            </Fragment>)
          ));
        }
      }
      </Query>

This is gql.

export const USER_QUERY = gql`
query{
    getUsers{
        gender
        age
        job
        location {
            dailyMovingAverage
            home
            mostStayingArea
            office
        }
        history {
            dateInformation {
                monthly {
                    month
                    favorateTransitionService
                    movingCarRate

                }
                daily {
                    date
                    movingCarRate
                }
            }
        }
    }
}

This is json data.

{
  "data": {
    "getUsers": [
      {
        "gender": "F",
        "age": "26",
        "job": "student",
        "location": {
          "dailyMovingAverage": 3,
          "home": "aaa",
          "mostStayingArea": "aaaa",
          "office": "aaa"
        },
        "history": {
          "dateInformation": [
            {
              "monthly": [
                {
                  "month": "March",
                  "favorateTransitionService": "Car",
                  "movingCarRate": 0,
...
Marco Daniel
  • 5,467
  • 5
  • 28
  • 36
J184937
  • 67
  • 2
  • 8
  • Grabbing `"March"` from that: `result.data.getUsers[0].history.dateInformation[0].monthly.month` (so all you need is add `[0]` after `getUsers`, apparently) –  May 08 '19 at 07:25
  • Thank you, Chris! It's working! But I have a lot of data to approach, so I want to generalize using map method. – J184937 May 08 '19 at 07:52
  • To iterate over all the data, you need to nest multiple map calls. Basically: `result.data.getUsers.map(user => user.historydateInformation.map(hdi => hdi.monthly.map(x => x.month)))` –  May 08 '19 at 07:59
  • Thank you so much, Chris !!! – J184937 May 08 '19 at 08:31

0 Answers0