
const desk = height: "4 feet", weight: "30 pounds", color: "brown", material: "wood", ;An object contains properties, or key-value pairs. The desk object above has four properties. Each property has a name, which is also called a key, and a corresponding value.
For instance, the key height has the value "4 feet". Together, the key and value biến hóa a single property.
height: "4 feet",The desk object contains data about a desk. In fact, this is a reason why you’d use a JavaScript object: lớn store data. It’s also simple khổng lồ retrieve the data that you store in an object. These aspects make objects very useful.
This article will get you up và running with JavaScript objects:
how to lớn create an object how lớn store data in an objectand retrieve data from it.Bạn đang xem: How to access object's keys, values, and entries in javascript
Let’s start by creating an object.
How to lớn Create an Object in JavaScriptI"ll create an object called pizza below, and showroom key-value pairs to lớn it.
const pizza = topping: "cheese", sauce: "marinara", size: "small";The keys are to lớn the left of the colon : and the values are khổng lồ the right of it. Each key-value pair is a property. There are three properties in this example:
The key topping has a value “cheese”.The key sauce has a value “marinara”.The key size has a value “small”.Each property is separated by a comma. All of the properties are wrapped in curly braces.
This is the basic object syntax. But there are a few rules to keep in mind when creating JavaScript objects.
ADVERTISEMENT
Object Keys in JavaScript
Each key in your JavaScript object must be a string, symbol, or number.
Take a close look at the example below. The key names 1 & 2 are actually coerced into strings.
const shoppingCart = 1: "apple", 2: "oranges";It’s a difference made clear when you print the object.
console.log(shoppingCart);//Result: "1": "apple", "2": "oranges" There’s another rule lớn keep in mind about key names: if your key name contains spaces, you need to lớn wrap it in quotes.
Take a look at the programmer object below. Notice the last key name, "current project name" . This key name contains spaces so, I wrapped it in quotes.
const programmer = firstname: "Phil", age: 21, backendDeveloper: true, languages: <"Python", "JavaScript", "Java", "C++">, "current project name": "The Amazing App";
Object Values in JavaScript
A value, on the other hand, can be any data type, including an array, number, or boolean. The values in the above example contain these types: string, integer, boolean, và an array.You can even use a function as a value, in which case it’s known as a method. Sounds(), in the object below, is an example.
const animal = type: "cat", name: "kitty", sounds() console.log("meow meow") ;Now say you want to địa chỉ cửa hàng or delete a key-value pair. Or you simply want khổng lồ retrieve an object’s value.
You can vì chưng these things by using dot or bracket notation, which we’ll tackle next.
ADVERTISEMENT
How Dot Notation và Bracket Notation Work in JavaScript
Dot notation & bracket notation are two ways khổng lồ access và use an object’s properties. You’ll probably find yourself reaching for dot notation more often, so we"ll start with that.
How to địa chỉ cửa hàng a Key-Value Pair with Dot Notation in JavaScript
I"ll create an empty book object below.
const book = ;To showroom a key-value pair using dot notation, use the syntax:
objectName.keyName = value
This is the code to địa chỉ cửa hàng the key (author) & value ("Jane Smith") to lớn the book object:
book.author = "Jane Smith";Here"s a breakdown of the above code:
book is the object"s name. (dot)author is the key name = (equals)"Jane Smith" is the valueWhen I print the book object, I’ll see the newly added key-value pair.
console.log(book);//Result: author: "Jane Smith" I’ll địa chỉ another key-value pair to lớn the book object.
book.publicationYear = 2006;The book object now has two properties.
console.log(book);//Result: author: "Jane Smith", publicationYear: 2006
ADVERTISEMENT
How lớn Access Data in a JavaScript Object Using Dot Notation
You can also use dot notation on a key khổng lồ access the related value.Consider this basketballPlayer object.
const basketballPlayer = name: "James", averagePointsPerGame: 20, height: "6 feet, 2 inches", position: "shooting guard";Say you want to lớn retrieve the value “shooting guard.” This is the syntax to use:
objectName.keyName
Let"s put this syntax to use khổng lồ get and print the "shooting guard" value.
console.log(basketballPlayer.position);//Result: shooting guardHere"s a breakdown of the above code:
basketballPlayer is the object"s name. (dot)position is the key nameThis is another example.
console.log(basketballPlayer.name);//Result: James
How to Delete a Key-Value Pair in JavaScript
To delete a key-value pair use the delete operator. This the syntax:delete objectName.keyName
So lớn delete the height key & its value from the basketballPlayer object, you’d write this code:
delete basketballPlayer.height;As a result, the basketballPlayer object now has three key-value pairs.
console.log(basketballPlayer);//Result: name: "James", averagePointsPerGame: 20, position: "shooting guard" You’ll probably find yourself reaching for dot notation frequently, though there are certain requirements lớn be aware of.
When using dot notation, key names can’t contain spaces, hyphens, or start with a number.
Xem thêm: Nhạc Chuông Liên Minh Huyền Thoại Teemo, Tải Captain Teemo On Duty (Nhạc Chuông) Mp3
For example, say I try to địa chỉ cửa hàng a key that contains spaces using dot notation. I’ll get an error.
basketballPlayer.shooting percentage = "75%";//Results in an errorSo dot notation won’t work in every situation. That’s why there’s another option: bracket notation.
ADVERTISEMENT
How to địa chỉ a Key-Value Pair Using Bracket Notation in JavaScript
Just like dot notation, you can use bracket notation to showroom a key-value pair lớn an object.
Bracket notation offers more flexibility than dot notation. That’s because key names can include spaces và hyphens, and they can start with numbers.
I"ll create an employee object below.
const employee = ;Now I want to add a key-value pair using bracket notation. This is the syntax:
objectName<“keyName”> = value
So this is how I’d showroom the key (occupation) & value (sales) khổng lồ the employee object:
employee<"occupation"> = "sales";Here"s a breakdown of the above code:
employee is the object"s name"occupation" is the key name = (equals)"sales" is the valueBelow are several more examples that use bracket notation"s flexibility to showroom a variety of key-value pairs.
//Add multi-word key nameemployee<"travels frequently"> = true; //Add key name that starts with a number & includes a hyphenemployee<"1st-territory"> = "Chicago"; //Add a key name that starts with a numberemployee<"25"> = "total customers";When I print the employee object, it looks like this:
"25": "total customers", occupation: "sales", "travels frequently": true, "1st-territory": "Chicago"With this information in mind, we can địa chỉ the “shooting percentage” key khổng lồ the basketballPlayer object from above.
const basketballPlayer = name: "James", averagePointsPerGame: 20, height: "6 feet, 2 inches", position: "shooting guard";You may remember that dot notation left us with an error when we tried to add a key that included spaces.
basketballPlayer.shooting percentage = "75%";//Results in an errorBut bracket notation leaves us error-free, as you can see here:
basketballPlayer<"shooting percentage"> = "75%";This is the result when I print the object:
name: "James", averagePointsPerGame: 20, height: "6 feet, 2 inches", position: "shooting guard", "shooting percentage": "75%"
How lớn Access Data in a JavaScript Object Using Bracket Notation
You can also use bracket notation on a key to access the related value.Recall the animal object from the start of the article.
const animal = type: "cat", name: "kitty", sounds() console.log("meow meow") ;Let"s get the value associated with the key, name. To vày this, wrap the key name quotes & put it in brackets. This is the syntax:
objectName<“keyName”>
Here"s the code you"d write with bracket notation: animal<"name">;.
This is a breakdown of the above code:
animal is the object"s name<"name"> is the key name enclosed in square bracketsHere’s another example.
console.log(animal<"sounds">());//Result: meow meowundefinedNote that sounds() is a method, which is why I added the parentheses at the over to invoke it.
This is how you’d invoke a method using dot notation.
console.log(animal.sounds());//Result: meow meowundefined
JavaScript Object MethodsYou know how lớn access specific properties. But what if you want all of the keys or all of the values from an object?
There are two methods that will give you the information you need.
const runner = name: "Jessica", age: 20, milesPerWeek: 40, race: "marathon";Use the Object.keys() method to retrieve all of the key names from an object.
This is the syntax:
Object.keys(objectName)
We can use this method on the above runner object.
Object.keys(runner);If you print the result, you’ll get an array of the object’s keys.
console.log(Object.keys(runner));//Result: < "name", "age", "milesPerWeek", "race" >Likewise, you can use the Object.values() method khổng lồ get all of the values from an object. This is the syntax:
Object.values(objectName)
Now we"ll get all of the values from the runner object.
console.log(Object.values(runner));//Result: < "Jessica", 20, 40, "marathon" >We’ve covered a lot of ground. Here’s a summary of the key ideas:
Objects:
Use objects to lớn store data as properties (key-value pairs).Key names must be strings, symbols, or numbers.Values can be any type.Access object properties:
Dot notation: objectName.keyNameBracket notation: objectName<“keyName”>Delete a property:
delete objectName.keyNameThere’s a lot you can vì chưng with objects. Và now you’ve got some of the basics so you can take advantage of this powerful JavaScript data type.
I write about learning to lớn program, & the best ways lớn go about it on amymhaddad.com. I also tweet about programming, learning, và productivity: Programmer and writer | howtolearneffectively.com | dailyskillplanner.com Learn to code for free. darkedeneurope.com"s mở cửa source curriculum has helped more than 40,000 people get jobs as developers. Get started darkedeneurope.com is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546) Our mission: lớn help people learn to code for free. We accomplish this by creating thousands of videos, articles, và interactive coding lessons - all freely available khổng lồ the public. We also have thousands of darkedeneurope.com study groups around the world. Donations khổng lồ darkedeneurope.com go toward our education initiatives, and help pay for servers, services, & staff.