如何将数组转换为数组对象并将两个数组合并为一个数组?

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并映射新对象。

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

  • @SinanYaman correct. [It's a curried function](https://stackoverflow.com/questions/32782922/what-do-multiple-arrow-functions-mean-in-javascript)

以上是如何将数组转换为数组对象并将两个数组合并为一个数组?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>