Understand Objects
What is an object?
An object is a data structure that holds related variables.
Object Syntax
An object is declared like any other variable. The object wraps related variables in curly braces {}
.
Instead of declaring variables in an object with let variableName = 'some data'
, the variables in an object use a colon to separate the variable and the data variableName: 'some data'
. The variable is called the key and the data is called the value - together they are a key-value pair.
Below is an object with the variable name aPersonObject
and three key-value pairs.
let aPersonObject = {name: 'Andrea',age: 39,country: 'USA'}
Accessing and Changing an Object
Accessing a value
There are two ways to access an object value.
One way is to type the key inside of quotes and a bracket after the object name. Note we use quotes because the keys are strings when created in the way you have learned.
let aPersonObject = {name: 'Andrea',age: 39,country: 'USA'}console.log(aPersonObject['name']); // prints 'Andrea'
The second way is type the key after the object name and a period.
let aPersonObject = {name: 'Andrea',age: 39,country: 'USA'}console.log(aPersonObject.name); // prints 'Andrea'
Changing or Adding to an Object
To change or add a key-value pair to an object you use the same syntax you used to access a value then you assign it to a value.
let aPersonObject = {name: 'Andrea',age: 39,country: 'USA'}console.log(aPersonObject); // {name: "Andrea", age: 39, country: "USA"}// adding a new key-value pairaPersonObject.city = 'San Francisco';console.log(aPersonObject); // {name: "Andrea", age: 39, country: "USA", city: "San Francisco"}// changing an old key-value pairaPersonObject.name = 'Ravi';console.log(aPersonObject); // {name: "Ravi", age: 39, country: "USA", city: "San Francisco"}
Methods
Object.keys(x)
The Object.keys(x) method takes the object as a parameter and returns a new array with the keys as array items.
let aPersonObject = {name: 'Andrea',age: 39,country: 'USA'}let aPersonArrayWithKeys = Object.keys(aPersonObject);console.log(aPersonArrayWithKeys); // ["name", "age", "country"]
Object.values(x)
The Object.values(x) method takes the object as a parameter and returns a new array with the values as array items.
let aPersonObject = {name: 'Andrea',age: 39,country: 'USA'}let aPersonArrayWithValues = Object.values(aPersonObject);console.log(aPersonArrayWithValues); // ["Andrea", 39, "USA"]