Cho mảng tên ['John','David','Bob'] và mảng object [{firstname:'Carol',marks:78},...]. Dùng Set và map() thêm thuộc tính isPresent cho object nếu firstname có trong mảng tên.
Mã thực hiện
const firstname = ['John', 'David', 'Bob'];
const studentDetails = [
{ firstname: 'Carol', marks: 78 },
{ firstname: 'Mike', marks: 89 },
{ firstname: 'Bob', marks: 86 }
];
const data = new Set(firstname);
const result = studentDetails.map(obj => {
if (data.has(obj.firstname)) obj.isPresent = "This is present";
else obj.isPresent = "This is not present";
return obj;
});
console.log(result);
Kết quả
[
{ firstname: 'Carol', marks: 78, isPresent: 'This is not present' },
{ firstname: 'Mike', marks: 89, isPresent: 'This is not present' },
{ firstname: 'Bob', marks: 86, isPresent: 'This is present' }
]