简体   繁体   中英

Accessing nested JSON data in React

Link to app: https://boiling-coast-12353.herokuapp.com/

Bear in mind this is for an assignment that does not require components yet (but will) What I have so far works, but now I would like to transform my data by using a nested JSON. Currently so I have JSON data that looks like this:

[
    { "label": "Argentina", "percentage": 10.44 },
    { "label": "Bolivia", "percentage": 51.62 },
     etc..
]

which I access to generate buttons and generates divs for each object in the array respectively:

{
  this.state.data.map((data, index) => (
  <button key={index}className="button-primary" onClick={() => 
  {this.onChooseCountry(index);}}>
     <span className="btn-content" tabindex="-1">
     </span>{data.label}</button>
  ))
} 

{
  this.state.chosenCountries.map((chosenCountry, index) => (
  <div className="bar--show bar" style={{height: chosenCountry.percentage + "%"}}>

  <h3>{chosenCountry.label}</h3>
  <h4>{chosenCountry.percentage} %</h4>
  <button className="remove-btn" onClick={() => this.removeCountry(index)}>remove</button>

 </div>
   ))
 }

The new data set I'd like to work with I've organized like this:

[
    { 
    "year": "2010",
     "info": [
        { "Country": "Argentina", "Percentage": 10.44 },
        { "Country": "Bolivia", "Percentage": 51.62 },
          ...
    ]
    },
    {
    "year":"2011",
    "info": [
        { "Country": "Argentina", "Percentage": 10.34 },
        { "Country": "Bolivia", "Percentage": 51.62 },
    ...

And I would like to pass the year/label for array into a select drop down menu:

<select onChange={this.updateYear} id="select" className="YearChooser-select">
   <option value="">Select Year</option>
   <option value="2016">2016</option>
   <option value="2015">2015</option>
   <option value="2014">2014</option>
   ...

</select>

Method Im using so far that gets the year value from the dropdown:

updateYear = (ev) => {

    this.setState({
      year: ev.target.value },
      () => console.log('update year', this.state.year));

  }

I figured out how to access the new nested data set using sub, but I don't know how to link the selected year from the drop down menu to the info for each year:

{
  this.state.data.map((datum) =>
  <div>
    {datum.year}
  <ul>
    {datum.info.map((sub) =>
    <div>
      {sub.Country} : 
       {sub.Percentage} %
    </div>
    )}
  </ul>
  </div>
  )
}
const options = this.state.data.map((datum) => (
    <option value={datum.year}>{datum.year}</option>
);

<select onChange={this.updateYear} id="select" className="YearChooser-select">
   {options}
</select>

is this what you looking for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM