Object.keys(obj) คืนอาร์เรย์ของชื่อพร็อพเพอร์ตี้ (keys) ที่เป็น Own Enumerable Properties ของอ็อบเจกต์ (ไม่รวม prototype chain, ไม่รวม Symbol properties, ไม่รวม non-enumerable)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Object.keys()</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>หา Keys ของอ็อบเจกต์ใน JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">แสดง Keys</button>
<h3>กดปุ่มเพื่อแสดง keys ของอ็อบเจกต์</h3>
<script>
const resEle = document.querySelector(".result");
const obj = {
firstName: "Rohan",
lastName: "Sharma",
age: 22,
};
document.querySelector(".Btn").addEventListener("click", () => {
resEle.textContent = "Keys: " + Object.keys(obj).join(", ");
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "แสดง Keys":

เมธอดที่เกี่ยวข้อง (Related Methods)
| เมธอด | คืนค่า | รวม Prototype? | รวม Symbol? | รวม Non-enumerable? |
|---|---|---|---|---|
Object.keys(obj) | String[] | ❌ | ❌ | ❌ |
Object.values(obj) | Any[] | ❌ | ❌ | ❌ |
Object.entries(obj) | [key, value][] | ❌ | ❌ | ❌ |
Object.getOwnPropertyNames(obj) | String[] | ❌ | ❌ | ✅ |
Object.getOwnPropertySymbols(obj) | Symbol[] | ❌ | ✅ | ❌ |
Reflect.ownKeys(obj) | (String|Symbol)[] | ❌ | ✅ | ✅ |
for...in loop | iterate keys | ✅ | ❌ | ❌ (เฉพาะ enumerable) |
ตัวอย่างเพิ่มเติม
const obj = { a: 1, b: 2, c: 3 };
Object.defineProperty(obj, "hidden", { value: 4, enumerable: false });
Object.defineProperty(obj, "sym", { value: 5, enumerable: true }); // Symbol key ต้องใช้ Symbol()
console.log(Object.keys(obj)); // ["a", "b", "c"]
console.log(Object.values(obj)); // [1, 2, 3]
console.log(Object.entries(obj)); // [["a",1], ["b",2], ["c",3]]
console.log(Object.getOwnPropertyNames(obj)); // ["a", "b", "c", "hidden"]
// Loop with keys
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
// Destructuring
const [first, second] = Object.keys(obj);
ประสิทธิภาพ
Object.keys()สร้างอาร์เรย์ใหม่ทุกครั้ง — หากเรียกในลูปเยอะ ควร cache ไว้- สำหรับการวนลูปเพียงครั้งเดียว ใช้
for (const key in obj)พร้อมhasOwnPropertyเช็ค - ใน Hot path ใช้
for...in+hasOwnPropertyเร็วกว่า (ไม่สร้าง array)