[英]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.