JavaScriptintermediate 8 min
Group related data with key-value pairs, read and change properties, and loop over them.
How to create an object, read and change its properties, add methods, and loop over keys and values.
A user has a name, an email and an age. Keeping those in separate variables is messy. An object bundles related information into one value, and it is the shape of nearly all data you receive from servers (JSON).
An object is a collection of key: value pairs in curly braces. The keys are called properties.
user.city = "Pune";delete user.age;"name" in user or user.name !== undefined.greet() { ... }. Inside, this is the object the method belongs to.Object.keys(obj), Object.values(obj) and Object.entries(obj) give arrays you can loop over.Objects can hold arrays and other objects, which is how you model real things.
user has a string, a number, an array and a method.user.greet() runs the method. this.name is Asha, so it prints Hi, I am Asha.city and change age.Object.entries(user) returns key-value pairs. We skip the function and print the rest: name, age, skills and city.name, so changing the copy does not affect the original: it prints Ravi Asha.Add a birthYear property and a method isAdult() that returns whether age >= 18.
obj.key looks for a property named "key". Use obj[key].this to be the object.const makes the object frozen. You can still change its properties.===. Two separate objects with the same contents are not equal.this is the object.{ ...obj }; loop with Object.entries.Next: changing web pages with the DOM.
const user = { name: "Asha", age: 30 };
console.log(user.name); // dot notation
console.log(user["age"]); // bracket notationconst user = {
name: "Asha",
age: 30,
skills: ["html", "css"],
greet() {
return "Hi, I am " + this.name;
},
};
console.log(user.greet());
user.city = "Pune";
user.age = 31;
for (const [key, value] of Object.entries(user)) {
if (typeof value !== "function") {
console.log(key, "=>", value);
}
}
const copy = { ...user, name: "Ravi" };
console.log(copy.name, user.name);