0

I'm trying to return data in an array of objects... I've done this before with JS, but it was a mess, was looking for a cleaner approach and slowly learning TS but i seem to have hit a wall...

export {};
const cheerio = require("cheerio");
const fetch = require("isomorphic-fetch");

interface PlayerStats {
  name: string;
  role: string;
  score: string;
  matches: string;
  totalBattles: number;
}

const fetchData = async (faction: string) => {
  const req = await fetch("https://localhost/3000/" + faction);
  const data: string = await req.text();
  const $ = cheerio.load(data);

  const SquadElements: Element[] = $("#teamDetails > div.memberList").toArray();

  const playerStats: PlayerStats[] = SquadElements.map((el: Element) => {
    const name: string = $(el).find(".member .name p").text() || "";
    const score: string = $(el).find(".member .stats .battlesWon").text();
    const matches: string = $(el).find(".member .stats .matchesPlayed").text();
    const role: string = $(el).find(".member .specialty h6").text();
    const totalBattles: number = parseInt(matches) * 3;

    return { name, score, matches, role, totalBattles };
  });

  console.log(playerStats[0]);
  return playerStats;
};
fetchData("9a7059e278");


console.log(playerStats[0]); returns name: 'name1name2name3name4name5'.. etc

2
  • 1
    Just guessing, but try moving .member from $(el).find() up here $("#teamDetails > div.memberList .member").toArray(); Commented Nov 15, 2021 at 13:40
  • It worked!! I am so happy and so annoyed at the same time haha, this was the fix, can't believe i didn't catch it... Thanks a bunch! Commented Nov 15, 2021 at 13:47

1 Answer 1

1

Thanks @Thomas for the help... It was as simple as:

$("#teamDetails > div.memberList > .member").toArray();

instead of:

$("#teamDetails > div.memberList").toArray();

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

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.