Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เพิ่ม property ให้รายการทั่วไปในอาร์เรย์และอาร์เรย์ของออบเจกต์ - JavaScript

เพื่อเพิ่ม property ใช้ 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' }
]