簡體   English   中英

如何將數組轉換為數組 object 並將兩個 arrays 合並為一個數組?

[英]How do I convert array to an array object and combine two arrays to a one array?

const absentStudentsId = [78, 15, 41, 30] // ======> [{stdId: 78, isPresent: false}, {stdId: 15, isPresent: false}, {stdId: 41, isPresent: false}, {stdId: 30, isPresent: false}]

const presentStudentsId = [80, 61] // ======> [{stdId: 80, isPresent: true}, {stdId: 61, isPresent: true}]

const students = [
  { stdId: 78, isPresent: false },
  { stdId: 15, isPresent: false },
  { stdId: 41, isPresent: false },
  { stdId: 30, isPresent: false },
  { stdId: 80, isPresent: true },
  { stdId: 61, isPresent: true },
]

我想實現您在注釋行中看到的邏輯。

您可以關閉isPresent和 map 個新對象。

 const buildObject = isPresent => stdId => ({ stdId, isPresent }), absentStudentsId = [78, 15, 41, 30], presentStudentsId = [80, 61], students = [...absentStudentsId.map(buildObject(false)), ...presentStudentsId.map(buildObject(true)) ]; console.log(students);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

.map() -> 遍歷數組元素並為每個項目返回一個新項目,並進行所需的計算。

...(Spread) -> 展開運算符,將數組擴展為單個元素。

let ans = [...(absentStudentsId.map(x => { return { stdId : x, present : false} })),...(presentStudentsId.map(x => {return { stdId : x, present : true} }))]

 const absentStudentsId = [78, 15, 41, 30] // ======> [{stdId: 78, isPresent: false}, {stdId: 15, isPresent: false}, {stdId: 30, isPresent: false}] const presentStudentsId = [80, 61] // ======> [{stdId: 80, isPresent: true}, {stdId: 61, isPresent: true}] const transformStudents = (students, isPresent) => students.map(studentId => ({ stdId: studentId, isPresent})); const allStudents = [...transformStudents(absentStudentsId, false), ...transformStudents(presentStudentsId, true)]; console.log(allStudents)

另一個直接的解決方案:

const absentStudentsId = [78, 15, 41, 30]
const presentStudentsId = [80, 61]

const students = []
absentStudentsId.forEach(id => students.push({stdID: id, isPresent: false}))
presentStudentsId.forEach(id => students.push({stdID: id, isPresent: true}))

console.log(students)
/*
[
  { stdID: 78, isPresent: false },
  { stdID: 15, isPresent: false },
  { stdID: 41, isPresent: false },
  { stdID: 30, isPresent: false },
  { stdID: 80, isPresent: true },
  { stdID: 61, isPresent: true }
]
*/

暫無
暫無

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

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