簡體   English   中英

如何從 state 獲取對象數組並將對象的特定值推送到新數組中

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

我從我的 API 收到 json object 並將其推入我的 Z9ED39E2EA931586B73A985A69EZEF2。 object 有一個名為“等級”的字段。 該等級是具有稱為“標記”的字段的對象數組。

我想從所有對象中獲取“標記”並將其推入一個新數組 / state 以計算平均“標記”。

這是我的代碼,其中包含對我想做的事情的評論:

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

這是實習生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
            }]

你可以像這樣制作標記數組

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

除了遍歷整個等級數組,別無他法。 您可以使用 Array.map 或 for 循環來遍歷 Grades 數組。 如果解析的 object 像

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

您可以使用

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

現在標記將包含標記值列表。 您可以調用setMarks(marks)來更新 state。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM