简体   繁体   English

如何从 state 获取对象数组并将对象的特定值推送到新数组中

[英]How do I take an array of objects from state and push a specific value of the objects into a new array

I am receiving a json object from my API and I am pushing it into my state.我从我的 API 收到 json object 并将其推入我的 Z9ED39E2EA931586B73A985A69EZEF2。 That object has a field called "grades". object 有一个名为“等级”的字段。 That grades is an array of objects that have a field called "mark".该等级是具有称为“标记”的字段的对象数组。

I would like to take the "mark" from all the objects and push it into a new array / state in order to calculate the average "mark".我想从所有对象中获取“标记”并将其推入一个新数组 / state 以计算平均“标记”。

Here's my code that includes comments on what I would like to do:这是我的代码,其中包含对我想做的事情的评论:

const [trainee, setTrainee] = useState ({})

// state declaration for the trainee.grades.mark array
const [mark, setMark] = useState ([])

useEffect(() => {
    fetch(`/api/trainees/${match.params.id}`)
    .then(response => response.json())
    .then(json => setTrainee(json))
// something here that pushes all trainee.grades.mark into mark through setMark
}, [])


// function that takes the state Mark array and calculates the average of it
function arrayAverage(arr){
  //Find the sum
  var sum = 0;
  for(var i in arr) {
      sum += arr[i];
  }
  //Get the length of the array
  var numbersCnt = arr.length;
  //Return the average / mean.
  return (sum / numbersCnt);
}

// end result by calling the average calculator function and passing mark as an array in it

 <Typography className={classes.title} color="textSecondary" gutterBottom>
          AVERAGE GRADE
        </Typography>
        <Typography variant="body2" component="p">
            {arrayAverage(mark)}
        </Typography>
        <Divider />

Here's the trainee object这是实习生object

_id: String
fullName: String
age: Number
author: {}
department: String
endDate: Date
startDate: Date
status: String
grades: [{  ._id: String
            title: String
            text: String
            mark: Number
            }]

You could make marks array like this你可以像这样制作标记数组

useEffect(() => {
  fetch(`/api/trainees/${match.params.id}`)
  .then(response => response.json())
  .then(json => {
    setTrainee(json);
    setMark(json.grades.map(grade => grade.mark));
  })
}, [])

and to calculate average并计算平均值

function arrayAverage(arr){
  //Find the sum
  const sum = arr.reduce((accumulator, mark) => (accumulator + mark));
  return sum / arr.length;
}

There is no other way but to traverse through the entire array of grades.除了遍历整个等级数组,别无他法。 You can either use Array.map or a for loop to traverse the grades array.您可以使用 Array.map 或 for 循环来遍历 Grades 数组。 if the parsed object is like如果解析的 object 像

let response = {
  grades: [
    {
       mark: value
       ...
    },
    ...
  ]
}

You can use您可以使用

let marks = response.grades.map(grade => {
   return grade.mark;
})

Now marks will contain a list of mark values.现在标记将包含标记值列表。 You can call setMarks(marks) to update the state.您可以调用setMarks(marks)来更新 state。

暂无
暂无

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

相关问题 如何检查我推入对象的对象数组是否具有来自另一个对象数组的特定键值 - How to check if an array of objects where I push into objects has a specific key value from another array of objects 如何将对象推入同一个数组? - How do i push objects into the same array? 如何搜索对象数组并在数组 Angular 中推送新值 8 - How to search array of objects and push new value in array Angular 8 如何在Javascript对象数组中搜索特定值? - How do I search for a specific value in an array of objects in Javascript? 从数组对象的 arrays 创建新数组 arrays,具有特定值 - Create new array of arrays from arrays of objects of array , with specific value 知道这些对象在对象数组中,如何将道具及其值推送到不具有特定属性的对象 - How can I push a prop and its value to objects that don't have that specific property knowing that these objects are in an array of objects 在Typescript 2中,如何从对象数组中获取单个属性并分配给新数组? - In Typescript 2 how can I take single property from array of objects and assign to new array? 如何从对象数组中动态获取特定数据? - How do I grab specific data dynamically from an array of objects? 如何在反应状态下更新对象数组中特定键的值? - How to update value of a specific key in array of objects in react state? 如何将多个 json 对象数组分组为新对象? - How do I group multiples of an array of json objects into new objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM