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

เปลี่ยน Property ของ Object แบบมีเงื่อนไขใน JavaScript

ใช้ Logical AND (&&) ร่วมกับ Spread Operator เพื่อเพิ่ม Property ก็ต่อเมื่อเงื่อนไขเป็นจริง

ตัวอย่างโค้ด

let marksDetails = { Mark1: 33, Mark2: 89 };
let isBacklog = false;

console.log("Result when backlog is set to false===");
console.log({ ...marksDetails, ...(isBacklog === true && { Mark1: 33 }) });

isBacklog = true;
console.log("Result when backlog is set to true===");
console.log({ ...marksDetails, ...(isBacklog === true && { Mark1: 93 }) });

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo77.js)

ผลลัพธ์

Result when backlog is set to false=== { Mark1: 33, Mark2: 89 }
Result when backlog is set to true=== { Mark1: 93, Mark2: 89 }