An object is a set of key/value pairs: const pet = { name: "Rex", age: 3 };. Read with a dot, pet.name, or brackets, pet["name"], which also work with a key held in a variable. Assigning to a new key adds it; delete pet.age removes one; "age" in pet asks whether a key exists. Reading a missing key gives undefined rather than an error.
Object.keys(obj), Object.values(obj), and Object.entries(obj) give arrays you can loop over. Objects are references: two variables can point at the same object, and changes through one are visible through the other.
const pet = { name: "Rex", age: 3 };
pet.sound = "woof";
console.log(Object.keys(pet)); // ["name", "age", "sound"]
for (const [k, v] of Object.entries(pet)) console.log(k, v);Your task
Write describe(pet) returning "<name> is <age> years old", addSound(pet, sound) that adds a sound key and returns the same object, and countKeys(obj) returning how many keys an object has.
Hint 1
return `${pet.name} is ${pet.age} years old`;
Hint 2
pet.sound = sound; return pet; and Object.keys(obj).length
Show the solution
function describe(pet) {
return `${pet.name} is ${pet.age} years old`;
}
function addSound(pet, sound) {
pet.sound = sound;
return pet;
}
function countKeys(obj) {
return Object.keys(obj).length;
}