All models are wrong, but some are useful. -- George Box
let abby = {
'species': 'dog',
'color': 'brown',
spayed: true,
breed: 'mutt',
weight: 40,
'favorite activity': 'chasing squirrels'
}
let abby = {...}
is an assignment, setting the variable abby
to point to the object we just definedAn object is useful for putting many similar things together.
Let's make an object that maps a state's abbreviation to its full name
Type this in a NodeJS console:
let states = {
'VT': 'Vermont',
'CA': 'California',
'MA': 'Massachusetts',
'NY': 'New York'
}
You can get the properties of an object with either dots or brackets:
With Dots | With Brackets | The Value |
---|---|---|
states.VT |
states['VT'] |
'Vermont' |
states.CA |
states['CA'] |
'California' |
states.MA |
states['MA'] |
'Massachusetts' |
states.NY |
states['NY'] |
'New York' |
Both syntaxes are useful in different situations.
states['VT'] // 'Vermont'
states.VT // also 'Vermont'
=
(single equal sign)states.WY = 'Wyoming'
states['FL'] = 'Florida'
javascript
states.VT = 'The Green Mountain State'
Dots are prettier than square brackets, but less versatile, since some keys simply cannot be represented using dot notation, and trying to use them causes syntax errors.
The bracket []
syntax is less common but covers more uses (e.g., if the key contains spaces, or is inside a variable).
> let capitals = {}
{}
> capitals.New York = 'Albany'
capitals.New York = 'Albany'
^^^^
SyntaxError: Unexpected identifier
> capitals.'New York' = 'Albany'
capitals.'New York' = 'Albany'
^^^^^^^^^^
SyntaxError: Unexpected string
If you get those errors, revert to brackets, which is more reliable:
> capitals['New York'] = 'Albany'
'Albany'
> capitals
{ 'New York': 'Albany' }
You can use variables instead of literals to get and set properties.
Given this code ...
let items = {
brick: 'red'
}
let item = 'brick'
... two of the following expressions look for a key named item
, but only one looks for a key named the value of the variable named item:
code | value | explanation |
---|---|---|
items.item |
undefined |
"get me the property named 'item'" |
items['item'] |
undefined |
"get me the property named 'item'" |
items[item] |
'red' |
"get me the property named 'brick'" |
This can be confusing!
Objects are good for a lot more than mere one-to-one maps. They allow you to design data structures that are as complicated and as deeply nested as you can imagine...
let alice = {
name: 'Alice Abrams',
age: 36,
married: false,
homeAddress: {
street: '12 Maple St.',
city: 'Burlington',
state: 'VT',
zipCode: '05401',
location: {
latitude: 44.4759,
longitude: -73.2121
}
},
pets: ['Mittens', 'Fido']
}
Given the above, the value of alice.homeAddress.zipCode
is '05401'
Note: The above shows the essence of JSON: a syntax for representing data structures containing primitive values, including nested objects and arrays.
Object.keys
Object.keys
is a special function that:
Example:
Object.keys(states) //=> [ 'CA', 'MA', 'NY' ]
Here's a way to loop through every property in an object.
This for..in
loop grabs every property in the states
object,
one at a time,
and inside the loop,
sets the state
value to that property's key
for (let state in states) {
}
In your NodeJS console, try to write code that outputs:
CA is short for California
MA is short for Massachusetts
NY is short for New York
Solution:
for (let state in states) {
console.log(state + ' is short for ' + states[state]);
}
Note: use "for...of
" for arrays, use "for...in
" for objects -- see this article for more detail about of vs. in.
WARNING: remember the let
or you will be defining a global variable named state
Please create a new file called gpa.js
, and type in the following code
(which defines a grades
object and calls a gpa
function):
let grades = {
'midterm': 3.3,
'project': 4.0,
'final': 3.2
}
console.log('The GPA is ' + gpa(grades));
gpa
function, and run node gpa
!Hint: There's more than one way to solve this!
In a JavaScript object, keys must be strings
Beware of using these as keys, since they get converted to strings in unexpected ways:
null
undefined
''
(empty string)false
or true
0
(or any number)delete
To remove a key-value pair from an object, use the keyword delete
:
states = {
CA: 'California',
MA: 'Massachusetts',
NY: 'New York'
}
{ CA: 'California', MA: 'Massachusetts', NY: 'New York' }
> delete states.MA
true
> states
{ CA: 'California', NY: 'New York' }
note that
delete
is not a function; it's a keyword
You can get a similar effect by setting the value to null
or undefined
, but beware: the key remains!
> states.CA = null
null
> states.NY = undefined
undefined
> states
{ CA: null, NY: undefined }
> for (let state of states) { console.log(state) }
Remember, this only removes the value, but not the key, from the property list. This can be dangerous!
order.js
.Item | Price |
---|---|
Burger | $5.00 |
Fries | $3.50 |
Shake | $1.11 |
Salad | $4.25 |
$ node order burger fries
Your order total is $8.50
$ node order burger burger shake fries burger
Your order total is $19.61
Here's a taste of object instance methods.
A method is a function attached to an object as a property.
let stringUtils = {
capitalize: function(word) {
return word.charAt(0).toUpperCase() +
word.slice(1).toLowerCase();
},
rant: function(opinion) {
return option.toUpperCase() + '!!!';
}
}
stringUtils.rant('i love pizza') //=> 'I LOVE PIZZA!!!'
/