เพิ่ม property lastName ตามเงื่อนไข studentName อยู่ใน join_values หรือไม่
ใช้ Object.assign() ร่วมกับ Object.keys().map() สร้างออบเจกต์ใหม่
ตัวอย่างโค้ด
const details = {
john: { 'studentName': 'John' },
david: { 'studentName': 'David' },
mike: { 'studentName': 'Mike' },
bob: { 'studentName': 'Bob' },
carol: { 'studentName': 'Carol' }
};
const join_values = ['David', 'Carol'];
const output = Object.assign(
{},
...Object.keys(details).map(key => ({
[key]: {
...details[key],
lastName: join_values.includes(details[key].studentName) ? 'Miller' : 'Smith'
}
}))
);
console.log(output);
วิธีรัน
node fileName.js
ผลลัพธ์
{
john: { studentName: 'John', lastName: 'Smith' },
david: { studentName: 'David', lastName: 'Miller' },
mike: { studentName: 'Mike', lastName: 'Smith' },
bob: { studentName: 'Bob', lastName: 'Smith' },
carol: { studentName: 'Carol', lastName: 'Miller' }
}
คำอธิบาย
Object.keys(details).map()สร้างอาร์เรย์ของออบเจกต์ { [key]: {...} }...details[key]spread property เดิมทั้งหมดlastName: condition ? 'Miller' : 'Smith'เพิ่ม property ใหม่ตามเงื่อนไขObject.assign({}, ...array)รวมอาร์เรย์ของออบเจกต์เป็นออบเจกต์เดียว
วิธีเข้าใจง่ายกว่า: ใช้ for...in
const output = {};
for (const key in details) {
output[key] = {
...details[key],
lastName: join_values.includes(details[key].studentName) ? 'Miller' : 'Smith'
};
}