Để thêm thuộc tính, hãy sử dụng map (). Giả sử sau đây là mảng của chúng tôi -
const firstname = ['John', 'David', 'Bob'];
Sau đây là mảng đối tượng của chúng tôi -
const studentDetails = [
{
firstname: 'Carol',
marks: 78
},
{
firstname: 'Mike',
marks: 89
},
{
firstname: 'Bob',
marks: 86
}
]; Ví dụ
Sau đây là mã -
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); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo219.js.
Đầu ra
Kết quả như sau -
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' }
]