What do Object.keys, Object.values, Object.entries and Object.fromEntries do?
keys gives an array of own enumerable property names, values gives their values, and entries gives [key, value] pairs. fromEntries does the reverse and builds an object from pairs, which makes transforming objects easy.
Explain it simply
An object is like a fee receipt with labels and amounts. You often want just the labels, just the amounts, or both together to loop over.
Object.keys(obj): the labels.Object.values(obj): the amounts.Object.entries(obj): pairs like["tuition", 50000], perfect with destructuring infor...oformap.Object.fromEntries(pairs): pairs back into an object.
Combine entries, array methods and fromEntries to transform an object: turn it into entries, map over them, and rebuild. These only include the object's own, enumerable properties, not inherited ones.
Example
const fee = { tuition: 50000, hostel: 20000 };
console.log(Object.keys(fee)); // Output: ["tuition","hostel"]
console.log(Object.values(fee)); // Output: [50000,20000]
console.log(Object.entries(fee)); // Output: [["tuition",50000],["hostel",20000]]
const total = Object.values(fee).reduce((a, n) => a + n, 0);
console.log(total); // Output: 70000
const doubled = Object.fromEntries(
Object.entries(fee).map(([k, v]) => [k, v * 2])
);
console.log(doubled); // Output: {"tuition":100000,"hostel":40000}What to say in the interview
"keys, values and entries return arrays of an object's own enumerable properties. entries pairs work nicely with destructuring, and fromEntries rebuilds an object, so entries, map and fromEntries is my pattern for transforming objects."
Common mistakes
- Using for...in and forgetting it also visits inherited enumerable properties.
- Expecting Object.keys to return symbol keys. It does not.