繁体   English   中英

如何从JSON对象数组中检索不同类型的数据并进行处理?

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

给出了一个JSON对象数组:

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"
}]

我想获得每个科目的最高分数,以及获得该分数的学生的姓名。

打印所有科目的总得分> 60分的学生总数。

在所有科目中,全班平均得分是多少?

课堂上最高分的总分数是多少? 在所有主题中打印名称和分数总和。

等等

对于最大分数,我尝试过:

 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>
    );
  }

错误:

第116行:未定义'getMax'no-undef
第121行:未定义'getMax'no-undef
第126行:“ getMax”未定义为no-undef

除此之外,另一个问题的逻辑是什么。

在codepen / jsfinddle上工作代码的链接会很棒。

到这里,只需单击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); 

要调用getMax方法,您需要使用this.getMax()

像那样:

 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>
    );
  }

您无需初始化组件即可工作,而是通过简单示例来阐明概念:

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'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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