Enumerate object keys, values and entries
Quick answer
Object.keys, Object.values and Object.entries return arrays derived from enumerable own string-keyed properties. They exclude inherited and symbol-keyed properties.
How it works
Keys gives names, values gives values, entries gives two-item arrays of key and value. For ordinary objects, array-index keys are ordered numerically first, followed by other string keys in creation order. Use these methods rather than assuming all objects have array indices.
const item = { name: "pen", stock: 4 };console.log(Object.keys(item).join(","));console.log(Object.values(item).join(","));Expected output in Node.js:
name,stockpen,4Names and values appear in corresponding enumeration order.
const scores = { math: 8, art: 9 };for (const entry of Object.entries(scores)) console.log(entry[0], entry[1]);Expected output in Node.js:
math 8art 9Each entry is a two-element array.
Common mistakes
Do not treat Object.keys as all possible keys. It omits symbols, non-enumerable fields and inherited fields. Null and undefined are invalid arguments.
Practice
Calculate the total of numeric values in a record using Object.values and a loop.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Enumerate object keys, values and entries — Knowledge Check
Apply the taught concept and reason about the result.
What does Object.keys({a:1,b:2}) return?
What does Object.values({a:1,b:2}) return?
What shape does each Object.entries result member have?
Does Object.keys include symbol-keyed properties?
What happens when Object.keys(null) is called?