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

时间:2019-04-12 02:47:08

标签: javascript json reactjs

有一个给定的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上的工作代码链接会很棒。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

要调用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>
    );
  }

答案 2 :(得分:0)

您不是要初始化组件才能正常工作,而是通过简单示例来阐明概念:

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