Javascript 如何从状态获取一个对象数组,并将对象的特定值推送到一个新数组中

Javascript 如何从状态获取一个对象数组,并将对象的特定值推送到一个新数组中,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我从API接收一个json对象,并将其推送到我的状态。该对象有一个名为“grades”的字段。这是一个对象数组,其中有一个名为“mark”的字段 我想从所有对象中提取“标记”,并将其推入新的数组/状态,以便计算平均“标记” 以下是我的代码,其中包括我想做的事情的注释: const [trainee, setTrainee] = useState ({}) // state declaration for the trainee.grades.mark array const [mark, se

我从API接收一个json对象,并将其推送到我的状态。该对象有一个名为“grades”的字段。这是一个对象数组,其中有一个名为“mark”的字段

我想从所有对象中提取“标记”,并将其推入新的数组/状态,以便计算平均“标记”

以下是我的代码,其中包括我想做的事情的注释:

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 />

除了遍历整个坡度阵列之外,没有其他方法。 可以使用Array.map或for循环遍历grades数组。 如果解析的对象与

let response = {
  grades: [
    {
       mark: value
       ...
    },
    ...
  ]
}
你可以用

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

现在,标记将包含标记值列表。您可以调用设置标记(marks)来更新状态。

除了遍历整个坡度数组之外,没有其他方法。 可以使用Array.map或for循环遍历grades数组。 如果解析的对象与

let response = {
  grades: [
    {
       mark: value
       ...
    },
    ...
  ]
}
你可以用

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

现在,标记将包含标记值列表。您可以调用设置标记(marks)来更新状态。

您可以这样创建标记数组

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

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

你可以这样做

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

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

请添加包含属性的
对象
好吗?我已经在上面添加了对象。请添加包含属性的
对象
好吗?我已经在上面添加了对象