Objects: properties, methods and JSON
Group related data into objects, add methods, loop over properties, use destructuring and spread, and convert to JSON.
In this lesson you will
- Create and change objects
- Write methods with this
- Work with arrays of objects
- Convert to and from JSON
About 18 minutes
Describing a thing with details
An array is a list, but real things have named details. A person has a name, an age and a city. A product has a title, a price and a stock count. Numbering them 0, 1 and 2 would be confusing. An object groups related values under names, called properties, like a form with labelled fields.
Creating and reading objects
const user = {
name: "Sara",
age: 28,
city: "Lahore",
isMember: true
};
console.log(user.name); // dot notation
console.log(user["city"]); // bracket notation
console.log(user.age + 1); // 29
Each property is written as key: value, separated by commas. Read a property with a dot. Use brackets with a string when the key is stored in a variable or contains unusual characters.
const field = "city";
console.log(user[field]); // "Lahore" - dynamic lookup
Changing, adding and deleting
user.age = 29; // change
user.email = "s@mail.com"; // add
delete user.isMember; // remove
console.log(user);
Create an object for a book with title, author and pages. Add a property read set to false, then change it to true and print the object.
// create the book
const book = { title: “…”, author: “…”, pages: 200 }; book.read = false;
const book = { title: "JS Basics", author: "Sara", pages: 200 };
book.read = false;
book.read = true;
console.log(book);
Methods: objects that can act
const counter = {
count: 0,
increase() {
this.count++;
},
show() {
console.log(`Count is ${this.count}`);
}
};
counter.increase();
counter.increase();
counter.show(); // Count is 2
Inside a method, this refers to the object the method belongs to. That is how increase knows which count to change. You have already used methods: console.log is a log method on the console object, and "hi".toUpperCase() is a method on a string.
Objects inside objects, and arrays of objects
const shop = {
name: "Book Corner",
address: { city: "Karachi", zip: "74000" },
books: [
{ title: "Learn JS", price: 500 },
{ title: "Learn CSS", price: 450 }
]
};
console.log(shop.address.city); // Karachi
console.log(shop.books[1].title); // Learn CSS
An array of objects is the most common shape for real data. A list of posts from a server, a table of customers, a product catalogue: they are all arrays of objects, and you already know how to loop and filter arrays.
Given the array of products, print the names of only those cheaper than 100, using filter and map.
const products = [
{ name: "Pen", price: 20 },
{ name: "Bag", price: 900 },
{ name: "Ruler", price: 60 }
];
// names of products under 100
products.filter(p => p.price p.name)
const products = [
{ name: "Pen", price: 20 },
{ name: "Bag", price: 900 },
{ name: "Ruler", price: 60 }
];
const cheap = products.filter(p => p.price < 100).map(p => p.name);
console.log(cheap);
Looping over an object
const scores = { maths: 90, english: 75, science: 82 };
for (const subject in scores) {
console.log(`${subject}: ${scores[subject]}`);
}
console.log(Object.keys(scores)); // ["maths","english","science"]
console.log(Object.values(scores)); // [90, 75, 82]
console.log(Object.entries(scores)); // pairs
Destructuring and spread
Two modern shortcuts make working with objects pleasant.
const user = { name: "Sara", age: 28, city: "Lahore" };
// destructuring: pull out several properties at once
const { name, city } = user;
console.log(name, city);
// spread: copy and override
const older = { ...user, age: 29 };
console.log(older); // user is unchanged
JSON: objects as text
When data travels between a browser and a server, it is sent as text in a format called JSON, which looks almost exactly like a JavaScript object. Two functions convert between the two.
const user = { name: "Sara", age: 28 };
const text = JSON.stringify(user);
console.log(text); // {"name":"Sara","age":28}
const back = JSON.parse(text);
console.log(back.name); // Sara
Reading a property that does not exist and then going deeper: user.address.city throws an error if address is undefined. Use optional chaining, user.address?.city, which returns undefined safely instead of crashing.
If you find yourself creating userName, userAge, userCity, stop and group them into one user object. You can pass it to functions as a single argument.
Worked example: a tiny shopping cart
A cart is an array of objects. Each item has a name, a price and a quantity. With the tools you know, you can compute the whole bill in a few lines.
const cart = [
{ name: "Notebook", price: 120, qty: 3 },
{ name: "Pen", price: 45, qty: 2 },
{ name: "Bag", price: 900, qty: 1 }
];
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
console.log(`Total: Rs ${total}`);
for (const { name, price, qty } of cart) {
console.log(`${name}: ${qty} x ${price} = ${qty * price}`);
}
This is the same structure that online shops use behind the scenes. When you later fetch data from a server, it will arrive as JSON, an array of objects that you can loop, filter and total exactly as above.
Add a new item to the cart with push, then print the number of items and the most expensive item name.
const cart = [
{ name: "Pen", price: 45 },
{ name: "Bag", price: 900 }
];
// push a new item, print count and priciest
Sort a copy by price descending, or loop and track the highest.
const cart = [
{ name: "Pen", price: 45 },
{ name: "Bag", price: 900 }
];
cart.push({ name: "Ruler", price: 60 });
console.log(cart.length);
const priciest = [...cart].sort((a, b) => b.price - a.price)[0];
console.log(priciest.name);
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
How do you read the name property of user?
user.nameuser(name)user->namename.user
Dot notation reads a property.
What is a function stored inside an object called?
- A method
- A loop
- A class only
- A string
It is called a method.
What does this refer to inside an object method?
- The window
- The object the method belongs to
- The previous line
- Nothing
this is the object calling the method.
What does JSON.stringify(obj) do?
- Converts an object to text
- Sorts the object
- Deletes it
- Converts text to an object
stringify makes a JSON string.
What does user.address?.city do when address is undefined?
- Throws an error
- Returns undefined
- Returns null
- Creates address
Optional chaining stops safely.
Summary
- Objects store named properties.
- Methods are functions inside objects.
- Arrays of objects hold most real data.
- JSON.stringify and parse convert to and from text.
Questions
When do I use an array and when an object?
Use an array for an ordered list of similar things, an object for one thing with named details.
What is the difference between dot and bracket notation?
Dot is simpler. Brackets let you use variables or unusual key names.
Can I compare two objects with ===?
Only if they are the exact same object. Two separate objects with equal contents are not ===.
