简体   繁体   中英

How to retrieve different type of data from JSON object array and play with it?

There is an Array of JSON object as given:

data: [{
    "name": "alice",
    "subject": "maths",
    "marks": "79"
},{
    "name": "bob",
    "subject": "maths",
    "marks": "36"
},{
    "name": "clare",
    "subject": "maths",
    "marks": "87"
},{
    "name": "dean",
    "subject": "maths",
    "marks": "50"
},{
    "name": "elon",
    "subject": "maths",
    "marks": "34"
},{
    "name": "fred",
    "subject": "maths",
    "marks": "99"
},{
    "name": "alice",
    "subject": "chemistry",
    "marks": "97"
},{
    "name": "bob",
    "subject": "chemistry",
    "marks": "80"
},{
    "name": "clare",
    "subject": "chemistry",
    "marks": "66"
},{
    "name": "dean",
    "subject": "chemistry",
    "marks": "83"
},{
    "name": "elon",
    "subject": "chemistry",
    "marks": "45"
},{
    "name": "fred",
    "subject": "chemistry",
    "marks": "32"
},{
    "name": "alice",
    "subject": "physics",
    "marks": "32"
},{
    "name": "bob",
    "subject": "physics",
    "marks": "29"
},{
    "name": "clare",
    "subject": "physics",
    "marks": "98"
},{
    "name": "dean",
    "subject": "physics",
    "marks": "56"
},{
    "name": "elon",
    "subject": "physics",
    "marks": "57"
},{
    "name": "fred",
    "subject": "physics",
    "marks": "62"
}]

I want to get the maximum marks scored in each subject and name of the student that scored that.

Print total no of students getting >60 marks across all subjects.

What is the average mark scored by the class across all subjects?

What is the sum of total marks scored by the topper in the class? Print with name and sum of marks in all subjects.

etc.

For max marks I tried:

 getMax = (arr, prop) => {
    var max;
    for (var i = 0; i < arr.length; i++) {
      if (!max || parseInt(arr[i][prop]) > parseInt(max[prop])) max = arr[i];
    }
    return max;
  };

  render() {
    return (
      <div className="App">
        <h1>
          {this.state.data.subject === "maths"
            ? getMax(this.state.data, this.state.data.marks)
            : ""}
        </h1>
        <h1>
          {this.state.data.subject === "physics"
            ? getMax(this.state.data, this.state.data.marks)
            : ""}
        </h1>
        <h1>
          {this.state.data.subject === "chemistry"
            ? getMax(this.state.data, this.state.data.marks)
            : ""}
        </h1>
      </div>
    );
  }

Error:

Line 116: 'getMax' is not defined no-undef
Line 121: 'getMax' is not defined no-undef
Line 126: 'getMax' is not defined no-undef

Apart from this what will be the logic for the other problem.

Link for the working code on codepen/jsfinddle will be great.

Here you go, just click Run code snippet :

 const data=[{name:"alice",subject:"maths",marks:"79"},{name:"bob",subject:"maths",marks:"36"},{name:"clare",subject:"maths",marks:"87"},{name:"dean",subject:"maths",marks:"50"},{name:"elon",subject:"maths",marks:"34"},{name:"fred",subject:"maths",marks:"99"},{name:"alice",subject:"chemistry",marks:"97"},{name:"bob",subject:"chemistry",marks:"80"},{name:"clare",subject:"chemistry",marks:"66"},{name:"dean",subject:"chemistry",marks:"83"},{name:"elon",subject:"chemistry",marks:"45"},{name:"fred",subject:"chemistry",marks:"32"},{name:"alice",subject:"physics",marks:"32"},{name:"bob",subject:"physics",marks:"29"},{name:"clare",subject:"physics",marks:"98"},{name:"dean",subject:"physics",marks:"56"},{name:"elon",subject:"physics",marks:"57"},{name:"fred",subject:"physics",marks:"62"}]; const getMax = (arr, prop) => arr .map(v => ({...v, [prop]: parseInt(v[prop])})) .reduce((a, c) => c[prop] > a[prop] ? c : a); const getMaxSubject = (arr, subject, prop) => getMax(arr.filter(v => v.subject === subject), prop); const aboveThreshold = (arr, threshold, prop) => arr .filter(v => parseInt(v[prop]) > threshold); const average = (arr, prop) => { const total = arr.reduce((a, c) => a + parseInt(c[prop]), 0); return total / arr.length; } const scoreSum = (arr, prop) => arr .reduce((a, c) => { let s = a.find(v => v.name === c.name); if (s === undefined) { s = { name: c.name, total: 0 }; a.push(s); } s.total += parseInt(c[prop]); return a; }, []); const mathsMax = getMaxSubject(data, 'maths', 'marks'); const chemistryMax = getMaxSubject(data, 'chemistry', 'marks'); const physicsMax = getMaxSubject(data, 'physics', 'marks'); const above60 = aboveThreshold(data, 60, 'marks'); const sums = scoreSum(data, 'marks'); const maxScore = getMax(sums, 'total'); // maximum marks scored in each subject and name of the student that scored that console.log('maths:', mathsMax.name, mathsMax.marks); console.log('chemistry:', chemistryMax.name, chemistryMax.marks); console.log('physics:', physicsMax.name, physicsMax.marks); // total no of students getting >60 marks across all subjects console.log('above 60:', above60.length); // average mark scored by the class across all subjects console.log('average:', average(data, 'marks')); // sum of total marks scored by the topper in the class console.log('max score:', maxScore.name, maxScore.total); 

To call the getMax method you need to use this.getMax()

Like that:

 getMax = (arr, prop) => {
    var max;
    for (var i = 0; i < arr.length; i++) {
      if (!max || parseInt(arr[i][prop]) > parseInt(max[prop])) max = arr[i];
    }
    return max;
  };

  render() {
    return (
      <div className="App">
        <h1>
          {this.state.data.subject === "maths"
            ? this.getMax(this.state.data, this.state.data.marks)
            : ""}
        </h1>
        <h1>
          {this.state.data.subject === "physics"
            ? this.getMax(this.state.data, this.state.data.marks)
            : ""}
        </h1>
        <h1>
          {this.state.data.subject === "chemistry"
            ? this.getMax(this.state.data, this.state.data.marks)
            : ""}
        </h1>
      </div>
    );
  }

You're not initializing the component to work, simple example to elucidate the concept:

class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {};
    this.getStringA = this.getStringA.bind(this);
    this.getStringB = this.getStringB.bind(this);
  }

  componentDidMount(){
    this.getStringA();
    this.getStringB();
  }

  getStringA(){
    let _state = this.state;
    _state['A'] = 'A';
    this.setState(_state);
  }

  getStringB(){
    let _state = this.state;
    _state['B'] = 'B';
    this.setState(_state);
  }

  render() {
    return (
      <div>
        Hello React..!<br/>
        {this.state.A}<br/>
        {this.state.B}
      </div>
    );
  }

}

React.render(<App />, document.getElementById('app'));

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