หากต้องการเพิ่มคุณสมบัติ ให้ใช้ map() สมมติว่าต่อไปนี้คืออาร์เรย์ของเรา –
const firstname = ['John', 'David', 'Bob'];
ต่อไปนี้เป็นอาร์เรย์ของวัตถุของเรา -
const studentDetails = [
{
firstname: 'Carol',
marks: 78
},
{
firstname: 'Mike',
marks: 89
},
{
firstname: 'Bob',
marks: 86
}
]; ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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(tmpObject => {
if (data.has(tmpObject.firstname)) tmpObject.isPresent ="This is present";
else
tmpObject.isPresent = "This is not present";
return tmpObject;
});
console.log(result); ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo219.js
ผลลัพธ์
ผลลัพธ์จะเป็นดังนี้ −
PS C:\Users\Amit\JavaScript-code> node demo219.js
[
{ 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' }
]