Toni Golac
Toni Golac

Reputation: 55

React how to parse through data

So, I have to iterate through data. I can successfully print the "round" value, but I can't get the matches, it only returns [object Object]. How can I get the data of matches?

I am new to mapping and new to React, I've tried everything. I just want to know how to print the values from the matches.

This is the Json file, by the way: https://s3.eu-central-1.amazonaws.com/js-assignment/data.json

import * as React from "react";
import "./App.css";

import logo from "./logo.svg";

class App extends React.Component {
  private data = require("./data.json");

  public constructor(props: Readonly<{}>) {
    super(props);
  }

  public componentDidMount() {
    this.getFootBallRounds();
  }

  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
      </div>
    );
  }

  private getFootBallRounds() {
    const data = require("./data.json"); // forward slashes will depend on the file location

    for (let i = 0; i < data.length; i++) {
      const obj = this.data[i];

      console.log("Round: " + obj.round);
    }
  }
}

export default App;

Upvotes: 1

Views: 116

Answers (1)

Roman Mahotskyi
Roman Mahotskyi

Reputation: 6625

You can get access to items of this.data by adding couple of lines.

for (let i = 0; i < data.length; i++) {
  const obj = this.data[i];

  for(let j = 0; j < data[i].matches.length; j++) {
    console.log(data[i].matches[j]); // <- Here is your item
  }

  console.log("Round: " + obj.round);
}

P.S. I have feeling that your console is not able to print an array and it shows you the [Object object] message. Try to print a particular item of your list (array).

Upvotes: 2

Related Questions