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

Ahm*_*him 0 javascript reactjs

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 },
]
Run Code Online (Sandbox Code Playgroud)

我想实现您在注释行中看到的逻辑。

Nin*_*olz 8

您可以关闭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);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)

  • @SinanYaman 正确。[这是一个柯里化函数](/sf/ask/2294804571/) (4认同)