1

Im trying to render and display nested json data but i have some issues this is the code.

import React, { useState, useEffect, useRef } from "react";
//import Moment from 'react-moment';
//import 'moment-timezone';
import moment from 'moment';


const dueTimes = [
  {
    distance: 6113,
    start: {
      time: moment().format("2020 7 1, 14, 38, 9"),
      address: "University College Dublin, Belfield, Dublin 4, Ireland",
      location: { lat: 53.30713120000001, lng: -6.220312 }
    },
    end: {
      time: moment().format("2020 7 1, 15, 2, 8"),
      address: "College Green, Dublin 2, Ireland",
      location: { lat: 53.3443633, lng: -6.2593112 }
    },
    steps: [
      {
        distance: 347,
        duration: 244,
        start: { lat: 53.30713120000001, lng: -6.220312 },
        stop: { lat: 53.309375, lng: -6.2187873 },
        mode: "WALKING"
      },
      {
        distance: 5445,
        duration: 968,
        start: { lat: 53.3094124, lng: -6.218878399999999 },
        stop: { lat: 53.3404818, lng: -6.2585706 },
        mode: "TRANSIT",
        transit: {
          dep: {
            name: "UCD N11 Entrance, stop 768",
            time: moment().format("2020 7 1, 14, 42, 13")
          },
          arr: {
            name: "Dawson Street, stop 792",
            time: moment().format("2020 7 1, 14, 58, 21")
          },
          headsign: "Ongar",
          type: "Dublin Bus",
          route: "39a"
        }
      },
      {
        distance: 321,
        duration: 226,
        start: { lat: 53.34212669999999, lng: -6.258003599999999 },
        stop: { lat: 53.3443633, lng: -6.2593112 },
        mode: "WALKING"
      }
    ]
  }
];

function Routes() {
    return (
        <div className="App">
            <div className="posts">
                {dueTimes.map(item => {
                    return (
                        <>
                            <h4>{item.distance}</h4>
                            <p>{item.start.time} </p>
                        </>

                    )
                })}
            </div>
        </div>
    );
}

export default Routes;

How can i render all of this data - i tried to add a nested map too but cant seem to get it to work. Yes im trying to display all of this data. When i tried to access a nested data i get "Error: Objects are not valid as a React child (found: object with keys {lat, lng}). If you meant to render a collection of children, use an array instead."

5
  • Would you like to show all the data from dueTimes? Commented Jul 2, 2020 at 13:01
  • jsonformatter.curiousconcept.com format your JSON, its hard to read. ;) Commented Jul 2, 2020 at 13:07
  • Hi yes @ShahnawazHossan I'm trying to display all the data from dueTimes, Commented Jul 2, 2020 at 13:14
  • and thank you @Emilis done :). Commented Jul 2, 2020 at 13:15
  • Have you tried Object.entries ? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 2, 2020 at 13:18

3 Answers 3

2
import * as React from "react";
import "./styles.css";
import moment from "moment";

const dueTimes = [
  {
    distance: 6113,
    start: {
      time: moment().format("2020 7 1, 14, 38, 9"),
      address: "University College Dublin, Belfield, Dublin 4, Ireland",
      location: {
        lat: 53.30713120000001,
        lng: -6.220312
      }
    },
    end: {
      time: moment().format("2020 7 1, 15, 2, 8"),
      address: "College Green, Dublin 2, Ireland",
      location: {
        lat: 53.3443633,
        lng: -6.2593112
      }
    },
    steps: [
      {
        distance: 347,
        duration: 244,
        start: {
          lat: 53.30713120000001,
          lng: -6.220312
        },
        stop: {
          lat: 53.309375,
          lng: -6.2187873
        },
        mode: "WALKING"
      },
      {
        distance: 5445,
        duration: 968,
        start: {
          lat: 53.3094124,
          lng: -6.218878399999999
        },
        stop: {
          lat: 53.3404818,
          lng: -6.2585706
        },
        mode: "TRANSIT",
        transit: {
          dep: {
            name: "UCD N11 Entrance, stop 768",
            time: moment().format("2020 7 1, 14, 42, 13")
          },
          arr: {
            name: "Dawson Street, stop 792",
            time: moment().format("2020 7 1, 14, 58, 21")
          },
          headsign: "Ongar",
          type: "Dublin Bus",
          route: "39a"
        }
      },
      {
        distance: 321,
        duration: 226,
        start: {
          lat: 53.34212669999999,
          lng: -6.258003599999999
        },
        stop: {
          lat: 53.3443633,
          lng: -6.2593112
        },
        mode: "WALKING"
      }
    ]
  }
];

export default function App() {
  return (
    <div className="App">
      <h1>Hello React Object Output</h1>
      {dueTimes.map(item => {
        return (
          <>
            <h4>Distance : {item.distance}</h4>
            <div>
              <h3>Start </h3>
              <p>Start Time: {item.start.time} </p>
              <p>Start address: {item.start.address} </p>
              <p>
                Start location: {item.start.location.lat} -{" "}
                {item.start.location.lng}{" "}
              </p>
            </div>
            <div>
              <h3>End </h3>
              <p>Start Time: {item.end.time} </p>
              <p>Start address: {item.end.address} </p>
              <p>
                Start location: {item.end.location.lat} -{" "}
                {item.end.location.lng}{" "}
              </p>
            </div>
            <div>
              <h3>steps </h3>
              <div>
                {item.steps.map((step, i) => {
                  return (
                    <div key={i}>
                      <p>Step mode: {step.mode}</p>
                      <p>Step Distance: {step.distance}</p>
                      <p>Step duration: {step.duration}</p>
                      {step.transit && (
                        <div>
                          <h5 style={{ background: "red", color: "white" }}>Transit</h5>
                          <p style={{ background: "yellow", color: "black" }}>Route: {step.transit?.route}</p>
                          <p style={{ background: "yellow", color: "black" }}>Type: {step.transit?.type}</p>
                          <p style={{ background: "yellow", color: "black" }}>headsign: {step.transit?.headsign}</p>
                          <p style={{ background: "yellow", color: "black" }}>dep.name: {step.transit?.dep.name}</p>
                          <p style={{ background: "yellow", color: "black" }}>dep.time: {step.transit?.dep.time}</p>
                          <p style={{ background: "yellow", color: "black" }}>arr.name: {step.transit?.arr.name}</p>
                          <p style={{ background: "yellow", color: "black" }}>arr.time: {step.transit?.arr.time}</p>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          </>
        );
      })}
    </div>
  );
}

https://codesandbox.io/s/async-rgb-nhmvy?file=/src/App.tsx:0-4119

here how you can.

you need to look for each array or object and iterate again

Sign up to request clarification or add additional context in comments.

4 Comments

Hey @Danish thank you it works and it makes more sense now! just have few questions of above. what is the use of the the parameter 'i' in the second map iteration and the key value i. Also why do you have "{step.transitt &&" does that check if there is a value in transit object and if there is render stuff?
Hi @overblown {step.transitt && ()} this is conditional rendering since now transit key was not present for all the steps. secondly parameter 'i' in the second map is key, Keys help React identify which items have changed, are added, or are removed. reactjs.org/docs/lists-and-keys.html#keys Please apply key to first map as well, i missed it :)
React is very slow , using that approach will throw exceptions if you are fast
ReactJS is slow? what you talking about @optimus, OP question is about ReactJS
1
const people = [
  {
    name: 'Mike Smith',
    family: {
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    name: 'Tom Jones',
    family: {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

for (const {name: n, family: {father: f}} of people) {
  console.log('Name: ' + n + ', Father: ' + f);
}

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

Try reading about decomposition here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment It helped me.

Comments

1

If I've got your question correctly, you want to know how to map some nested data.

import React, { Fragment } from "react";
import moment from "moment";

const dueTimes = [
  {
    distance: 6113,
    start: {
      time: moment().format("2020 7 1, 14, 38, 9"),
      address: "University College Dublin, Belfield, Dublin 4, Ireland",
      location: { lat: 53.30713120000001, lng: -6.220312 }
    },
    end: {
      time: moment().format("2020 7 1, 15, 2, 8"),
      address: "College Green, Dublin 2, Ireland",
      location: { lat: 53.3443633, lng: -6.2593112 }
    },
    steps: [
      {
        distance: 347,
        duration: 244,
        start: { lat: 53.30713120000001, lng: -6.220312 },
        stop: { lat: 53.309375, lng: -6.2187873 },
        mode: "WALKING"
      },
      {
        distance: 5445,
        duration: 968,
        start: { lat: 53.3094124, lng: -6.218878399999999 },
        stop: { lat: 53.3404818, lng: -6.2585706 },
        mode: "TRANSIT",
        transit: {
          dep: {
            name: "UCD N11 Entrance, stop 768",
            time: moment().format("2020 7 1, 14, 42, 13")
          },
          arr: {
            name: "Dawson Street, stop 792",
            time: moment().format("2020 7 1, 14, 58, 21")
          },
          headsign: "Ongar",
          type: "Dublin Bus",
          route: "39a"
        }
      },
      {
        distance: 321,
        duration: 226,
        start: { lat: 53.34212669999999, lng: -6.258003599999999 },
        stop: { lat: 53.3443633, lng: -6.2593112 },
        mode: "WALKING"
      }
    ]
  }
];

function Routes() {
  return (
    <div className="App">
      <div className="posts">
        {dueTimes.map((item, itemIndex) => {
          return (
            <Fragment key={itemIndex}>
              <h4>{item.distance}</h4>
              <p>{item.start.time}</p>
              <span>
                {item.steps.map((step, stepIndex) => (
                  <Fragment key={stepIndex}>
                    <p>{step.distance}</p>
                  </Fragment>
                ))}
              </span>
            </Fragment>
          );
        })}
      </div>
    </div>
  );
}

export default Routes;

Here an example.

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.