How do you iterate over an object's properties and which methods would you use? Explain `Object.keys`, `Object.values`, and `Object.entries`.
Show answer — try answering out loud first
Object.keys(obj) returns an array of the keys, Object.values(obj) of the values, and Object.entries(obj) of [key, value] pairs. With these arrays you can use map, filter, forEach, etc. to iterate over objects.
Objects don't have map or filter directly like arrays do. To iterate over them, you first convert them into arrays with:
Object.keys(obj): array of the keys.Object.values(obj): array of the values.Object.entries(obj): array of[key, value]pairs, ideal for iterating with destructuring.
Other useful methods:
Object.assign(destino, origen): copies properties (shallow).Object.freeze(obj): freezes the object so it can't be modified.
const producto = { nombre: "Laptop", precio: 1000, stock: 5 };
// Object.keys: the keys
console.log(Object.keys(producto)); // ["nombre", "precio", "stock"]
// Object.values: the values
console.log(Object.values(producto)); // ["Laptop", 1000, 5]
// Object.entries: [key, value] pairs
console.log(Object.entries(producto));
// [["nombre", "Laptop"], ["precio", 1000], ["stock", 5]]
// Iterate over an object with entries and destructuring
for (const [clave, valor] of Object.entries(producto)) {
console.log(`${clave}: ${valor}`);
}
// nombre: Laptop
// precio: 1000
// stock: 5
// Object.freeze: prevents modifications
const config = Object.freeze({ modo: "dark" });
config.modo = "light"; // ignored (or throws an error in strict mode)
console.log(config.modo); // "dark"
Trying to use producto.map(...) directly on an object: objects don't have map. You first have to convert them with Object.keys/values/entries. Another mistake is forgetting that Object.freeze is shallow: nested objects can still be modified.
"To iterate over an object I convert it into an array with
Object.keys,Object.values, orObject.entries.entriesis my favorite because it gives me key-value pairs that I can destructure in afor...of. Once I have those arrays I can applymap,filter, or whatever I need. I also knowObject.assignfor merging objects andObject.freezefor making them read-only, although the latter is shallow."
Given { a: 1, b: 2, c: 3 }, use the object methods to get the sum of all its values.
See answer
const obj = { a: 1, b: 2, c: 3 };
const suma = Object.values(obj).reduce((acc, n) => acc + n, 0);
console.log(suma); // 6