Home>

Continuation from the previous time.
​​https://www.tutorialfor.com/go.php?id=142016

We continue to get the following JSON.
https://worldcup.sfg.io/matches

The next step is

  1. Get home_team_events and away_team_events and combine two team_events
  2. Sort based on time, each team event is an object?
  3. I want to distinguish tags by looking at linked objects

I want to do that.

Image of what I want to do ↓

Japan vs Argentina
goal Kagawa 6
16 goal messi
goal Okazaki 26
50 Change Aguero
Tried

What I want to do 1 thought that it was necessary to concatenate arrays first, I didObject.assign ()incomponentWillMount ()It has become.

Current code
import React, {Component, Fragment} from 'react';
import styled from 'styled-components';
import axios from 'axios';
import User from './App.css'
const MatchItem = styled.div`
  max-width: 600px;
  margin: 0 auto 16px;
  border: 1px solid #ccc;
`;
const TeamWrap = styled.div`
  display: flex;
`;
const Team = styled.div`
  width: 100%;
  text-align: center;
  height: 60px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
`;
const MatchTexts = styled.div`
  min-width: 50px;
  flex-shrink: 0;
  display: flex;
  font-size: 12px;
  justify-content: center;
  align-items: center;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
`;
const MatchHeading = styled.div`
  text-align: center;
  background: # 333;
  color: #fff;
  font-weight: bold;
`;

const StatsWrap = styled.div``;
const GoalWrap = styled.div`
  display: flex;
`;
const Goal = styled.div`
  width: 100%;
  text-align: center;
  height: 30px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
`;
const EventWrap = styled.div``;
const EventDetail = styled.div`
  display: flex;
  &: not (: last-child) {
    border-bottom: 1px solid #eee;
  }
`;
const Event = styled.div`
  width: 100%;
  text-align: center;
  height: 30px;
  display: flex;
  align-items: center;
  font-size: 14px;
`;
const EventType = styled.div`
  width: 80px;
  height: 30px;
  font-size: 10px;
  flex-shrink: 0;display: flex;
  align-items: center;
  justify-content: center;
  background: # 333;
  ${({isGoal}) =>isGoal&&`
    color: #fff;
    font-weight: bold;
    }
  `}
  ${({isIn}) =>isIn&&`
    color: # a0d8ff;
  `}
  ${({isOut}) =>isOut&&`
    color: #ffcdcd;
  `}
  ${({isCardY}) =>isCardY&&`
    color: #fffacd;
  `}
  ${({isCardR}) =>isCardR&&`
    color: # ff6363;
  `}
`;
const EventPlayer = styled.div`
  width: 100%;
  text-align: center;
`;
class App extends Component {
  constructor () {
    super ();
    this.state = {
      matchDatas: []
    };
  }
  componentWillMount () {
    const request = axios.create ({
      baseURL: 'https://worldcup.sfg.io/'
    })
    request.get ('/ matches')
      .then (res =>{
        this.setState ({
          matchDatas: res.data
        });
      })
  }
  render () {
    return (
      <Fragment>
        {this.state.matchDatas.map ((item, index) =>(
          <MatchItem key = {index}>
            <TeamWrap>
              <Team>{item.home_team_country}</Team>
              <MatchTexts>vs</MatchTexts>
              <Team>{item.away_team_country}</Team>
            </TeamWrap>
            <StatsWrap>
              <MatchHeading>Stats</MatchHeading>
              <GoalWrap>
                <Goal>{item.home_team.goals}</Goal>
                <MatchTexts>Goal</MatchTexts>
                <Goal>{item.away_team.goals}</Goal>
              </GoalWrap>
            </StatsWrap>
            <EventWrap>
              <MatchHeading>Events</MatchHeading>
              {item.home_team_events.map ((matchHomeEvent, i) =>(
                <EventDetail key = {i}>
                  <Event>
                  {(() =>{
                    if (matchHomeEvent.type_of_event === 'goal') {
                      return (
                        <EventType isGoal>Goal !!!</EventType>
                      )
                    } else if (matchHomeEvent.type_of_event === 'goal-penalty') {
                      return (
                        <EventType isGoal>Goal (PK)</EventType>
                      )
                    } else if (matchHomeEvent.type_of_event === 'goal-own') {
                      return (
                        <EventType isGoal>Goal (OWN)</EventType>
                      )
                    } else if (matchHomeEvent.type_of_event === 'substitution-in') {
                      return (
                        <EventType isIn>In</EventType>
                      )
                    } else if (matchHomeEvent.type_of_event === 'substitution-out') {
                      return (
                        <EventType isOut>Out</EventType>
                      )
                    } else if (matchHomeEvent.type_of_event === 'yellow-card') {
                      return (
                        <EventType isCardY>Yellow Card</EventType>
                      )
                    } else if (matchHomeEvent.type_of_event === 'yellow-card-second') {
                      return (
                        <EventType isCardR>Yellow Card (2)</EventType>
                      )
                    } else if (matchHomeEvent.type_of_event === 'red-card') {
                      return (
                        <EventType isCardR>Red Card</EventType>
                      )
                    }
                  }) ()}
                    <EventPlayer>{matchHomeEvent.player}</EventPlayer>
                  </Event>
                  <MatchTexts>{matchHomeEvent.time}</MatchTexts>
                  <Event>aa</Event>
                </EventDetail>
              ))}
            </EventWrap>
          </MatchItem>
        ))}
      </Fragment>
    );
  }
}
export default App;


First of all, please realize what I want to do.

  • Answer # 1

    home_team_events and away_team_events are like arrays, so you can combine them with Array.concat.

    const allEvents = item.home_team_events.concat (item.away_team_events)

  • Answer # 2

    Until you find the function you want Process

    It's not particularly difficult, but are you investigating properly?

      

    1. Get home_team_events and away_team_events and combine two team_events

    If you look at the original JSON,

    https://worldcup.sfg.io/matches

    , "home_team_events": [{"id": 5, "type_of_event": "goal", "player": "Iury GAZINSKY", "time": "12 ' "}, {" id ": 1," type_of_event ":" substitution-in "," player ":" Denis CHERYSHEV "," time ":" 24 '"}, {" id ": 320," type_of_event ": "substitution-out", "player": "Alan DZAGOEV", "time": "24 '"}, {"id": 2, "type_of_event": "goal", "player": "Denis CHERYSHEV", " time ":" 43 '"},
    ...
    , "away_team_events": [{"id": 12, "type_of_event": "substitution-in", "player": "FAHAD ALMUWALLAD", "time": "64 '"}, {"id": 325, " type_of_event ":" substitution-out "," player ":" ABDULLAH OTAYF "," time ":" 64 '"},
    You can see that

    home_team_eventsandaway_team_eventsare arrays.
    Then you will only have to check if the array has the corresponding function.

    Array.prototype-JavaScript | MDN

    Although there is a difference between destructive and nondestructive, you can see that it has the following functions.

    Array.prototype.concat ()-JavaScript | MDN

    Array.prototype.push ()-JavaScript | MDN

    Spread element implemented-JS.next

      

    2. Sorting by time, each team event is an object?

    I know it's an array, so I'm looking for it as before,

    Array.prototype.sort ()-JavaScript | MDN

    How to check

    Reading the question history so far seems to have solved all the code, but firstlearn how.
    Anyone who can learn how to fish from fish is good, but questions that write only the requirements but do not write "I investigated myself" tend to be accepted as "round throw".

    StackOverflow's goal is fish, fishing, or ... (39089) | StackOverflow

    Re: www-www's

  • Answer # 3

    Hello.
    For questions

      

    First of all, thank you for realizing what you want to do.

    There was

    , but the answers below include things 2 and 3 you want to do. In that regard, I'm sorry if the answer is a little too messy.

    Based on three things that www-www wants to do, here is an example of a solution.
    (*I wrote the following code amendment in Addendum 1 and 2.)

    const timeValue = (timeStr) =>{
      const minutes = timeStr.split ("'");
      const value =
        parseInt (minutes [0], 10) +
        (minutes [1] .length>0? parseInt (minutes [1], 10): 0);
      return value;
    };
    const sortedEventsOfBothTeams = (item) =>(['home_team', 'away_team']
      .Reduce ((ary, team) =>{
              Item [`${team} _events`] .forEach ((event) =>{
                Ary.push ({
                       ... event,
                       team,
                       timeValue: timeValue (event.time),
                     });
                  });
                  return ary;
             }, [])
         .sort ((e1, e2) =>e1.timeValue-e2.timeValue)
    );

    A sample that creates<table>using the above code

    https://jsfiddle.net/jun68ykt/bw6o1ajx/67/

    I made a prototype. This is a modified version of https://jsfiddle.net/jun68ykt/bw6o1ajx/7/ that was created in response to the previous question.


    The following is a supplementary explanation of the two functions created above.

    (1)sortedEventsOfBothTeams (item)is a function that returns a combined array. When creating a combined array, the following two properties are added.

    team --- String"home_team"or"away_team"(used later fortag extraction)

    timeValue --- Value converted fromtimestring to numeric value bytimeValue ()(sorted in ascending order of this value)

    (2) The auxiliary functiontimeValue ()takes a string of occurrences returned in the response, such as&55;""This function converts code>55. The code"90'+ 3"after entering the additional time is also converted to the numerical value93.

       

    * In the following additions 1 and 2, the above two functions are revised.


    Appendix 1: an alternative to sortedEventsOfBothTeams

    In the above code, there wasforEachinreduce, and I felt it was difficult to understand at first glance.
    It seems to be easier to write by using concat in Kakajika's answer, starting with simply creating a combined array. We decided to add the property for sorting and sorting after the combination, and it became as follows.

    const sortedEventsOfBothTeams = (item) =>{
      const allEvents = item.home_team_events.concat (item.away_team_events);
      const homeTeamEventIds = item.home_team_events.map (event =>event.id);
      return allEvents
          .map (event =>({
              ... event,
              team: homeTeamEventIds.includes (event.id)? 'home_team': 'away_team',
              timeValue: timeValue (event.time),
          }))
         .sort ((e1, e2) =>e1.timeValue-e2.timeValue);
    };

    Sample: https://jsfiddle.net/jun68ykt/bw6o1ajx/79/


    Appendix 2: Alternative timeValue

    The reduce () used in the code for the first answer is useful in many ways. For example, the functiontimeValue (timeStr)in the answer can be written as follows when using reduce ().

    const timeValue = timeStr =>
      timeStr.split ("'"). reduce ((total, min) =>total + Number (min), 0);
    // Sum the numbers separated by 'as follows:
    console.log (timeValue ("5 '"));// =>5
    console.log (timeValue ("77 '"));// =>77
    console.log (timeValue ("90 '+ 11"));// =>101
    console.log (timeValue ("10 '+ 11'-5'20'4.5' + 0.01"));// =>40.51