Reputation: 517
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 },
]
I want to implement that logic as you see in the commented line.
Upvotes: 0
Views: 84
Reputation: 1025
Yet another straightforward solution:
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 }
]
*/
Upvotes: 1
Reputation: 5497
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)
Upvotes: 1
Reputation: 20626
.map() -> loop over array elements and return a new item for eachitem with your desired computation.
...(Spread) -> spread operator which expands an array into individual elements.
let ans = [...(absentStudentsId.map(x => { return { stdId : x, present : false} })),...(presentStudentsId.map(x => {return { stdId : x, present : true} }))]
Upvotes: 1
Reputation: 386816
You could take a closure over isPresent
and map new objects.
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; }
Upvotes: 8