5.8 Enumeration of properties of an object
Now that we know objects inside out, let's see how to enumerate their properties. The classic tool is the for...in loop combined with bracket notation. At each iteration we receive the key of one property and we read the matching value with object[key].
const another = {};
for (let key in circle) {
another[key] = circle[key];
}
console.log(another);
This is exactly what we'd do if we wanted to clone an object the old-fashioned way: walk every property and copy it into a new object. The new object holds the same radius property and the same draw method as the original.
Modern alternatives
Object.assign(target, source)— copies all properties from one or more source objects into a target. With an empty target, it acts as a one-line clone.{ ...circle }— the spread operator, the cleanest way to clone an object literal.- Both let you also pre-fill or override properties, like
Object.assign({ color: "yellow" }, circle).
const another = Object.assign({}, circle);
const clone = { ...circle };
Whichever syntax you pick, the idea is the same: enumerate the keys of an object and decide what to do with each one. In the next video we'll look more closely at cloning an object and what these techniques mean in practice.