JavaScript objects and JSON
// updated 2025-05-07 10:14
Objects encapsulate data (itself encapsulated in pairs of property and values):
- the key describes the value
- the value acts as a data point
- could consist of a simple string, number, object or even a function!
- a function that lives inside an object property is called a method
In this article, we will look at:
- Notation of JavaScript objects
- Accessing object properties
- Nested objects
- Removing object properties
- Verifying the existence of a property in an object
- Optional chaining operator
- Listing all of an object's properties
- JSON (JavaScript Object Notation)
Notation
Some examples of JavaScript objects:
1// the simplest object has an empty set of curly braces
2const emptyObject = {}
3
4// the simplest non-empty object has a key and some value
5const oneKeyObject = {
6 name: "Jon"
7}
8
9// objects can have properties which hold values of any data type:
10const complexObject = {
11 key1 : "Hello",
12 key2 : "Hey",
13 anotherKey : 42,
14 someOtherKey : true,
15 nestedObject : {
16 nestedObjectKey: true
17 },
18 method: function() {
19 return "Surprise!"
20 }
21}
22
23// example of an object used "in real life":
24const person = {
25 name : "Jon",
26 age : 100,
27 retired : false,
28 hobbies : ["travel", "languages", "sports"],
29 getAge : function() {
30 return this.age
31 }
32}
We can gather from the above that:
- the object has keys separated by commas
- keys can have names similar to variables
- but with no declaration keywords (no
const
/let
/var
)
- but with no declaration keywords (no
More abstractly, an object would look like:
1let value1 = "value1's value"
2
3keyword objectVariableName {
4 // assigning a variable
5 keyName1 : value1,
6 // assigning a string
7 keyName2 : "value2",
8 ...
9}
Some restrictions in JavaScript:
- the
keyword
would be eitherconst
,let
orvar
- the
objectVariableName
has to begin with a letter (no numerical digits)- also, all other characters must either be a letter or a number (no spaces)
- the
keyName
can include spaces but the name would have to be in "quotes"
1const object = {
2 "multi-word key" : "some value"
3}
Accessing object properties
To access an object property, we can use the following notations:
- dot notation, e.g.
objectVariableName.keyName1
- bracket notation, e.g.
objectVariableName["keyName1"]
object["multi-word key"]
Note that we cannot do multi-word key names with dot notation!
So, in code:
1console.log(objectVariableName.keyName1)
2// "value1's value"
3
4console.log(objectVariableName.keyName2)
5// "value2"
6
7console.log(objectVariableName["multi-word key"])
8// "some value"
Nested objects
We can even have objects within objects:
1const person = {
2 name: {
3 first: "Mark",
4 middle: "James",
5 last: "Park"
6 },
7 phone: {
8 personal: {
9 land: '555-111-1234'
10 mobile: '555-999-8875'
11 },
12 work: {
13 land: '000-000-0000'
14 }
15 }
16}
17
18console.log(person.name.last)
19// Park
20
21console.log(person["name"]["last"])
22// Park
23
24console.log(person["phone"]["personal"]["land"])
25// '555-111-1234'
As we can see, we can access the object properties using chained dot and/or bracket notation. We can also chain as many levels down as we wish. Both notations offer this robustness with all the conciseness!
Using destructuring to access properties of nested objects
We can access the value of a "nested property within a property" using a special syntax called destructuring:
1const complexObject = {
2 key1 : "Hi",
3 key2 : {
4 key2a : "2A",
5 key2b : "2B"
6 }
7}
8
9const { key2 : { key2a }} = complexObject
10console.log(key2a)
11// 2A
12
13const { key2 : { key2a, key2b }} = complexObject
14console.log(key2a, key2b)
15// 2A 2B
Removing object properties
For whatever reason, we can use the unary operator delete
to remove an object's property:
1const simpleObject = {
2 key1 : "Hi",
3 key2 : 100,
4 key3 : false
5}
6
7delete simpleObject.key2
8
9console.log(simpleObject.key2)
10// undefined
11
12console.log(simpleObject)
13// { key1 : "Hi", key3 : false }
Verifying the existence of a property in an object
To check if a property name exists in an object, we can use a simple built-in method called hasOwnProperty()
:
1const simpleObject = {
2 key1 : "Hi",
3 key2 : 100,
4 key3 : false,
5 key4 : null
6}
7
8console.log(simpleObject.hasOwnProperty("key1"))
9// true
10
11console.log(simpleObject.hasOwnProperty("key5"))
12// false
We can also use the in
operator if hasOwnProperty
takes too long to type:
1const simpleObject = {
2 key1 : "Hi",
3 key2 : 100,
4 key3 : false,
5 key4 : null
6}
7
8console.log("key1" in simpleObject)
9// true
10
11console.log("key5" in simpleObject)
12// false
Optional chaining operator
We can use the optional chaining operator (a question mark, ?
, after the property name) to avoid worrying about whether or not an object or a property exists:
1const simpleObject = {
2 key1 : "Hi",
3 key2 : 100,
4 key3 : false,
5 key4 : null
6}
7
8console.log(simpleObject.key5?.name)
9// undefined
10
11console.log(simpleObject?.key5)
12// undefined
In each case above, the code will throw no error but will return undefined
which we can handle accordingly.
Listing all of an object's properties
To output all the properties of an object, we can use a for ... in ...
loop to iterate through an object's keys and values:
1const myObject = {
2 firstName: "Jon",
3 lastName: "Coded",
4 age: 100
5}
6
7for (let key in myObject) {
8 console.log(key + ": " + myObject[key])
9}
10
11/* Output:
12firstName: Jon
13lastName: Coded
14age: 100
Breaking that down:
- we let
key
(the first variable) represent each property name ofmyObject
- then we use
in
to referencemyObject
- within the loop we access each key's value with
myObject[key]
key
could consist of any legal JavaScript property name
JSON
So, we will likely hear of JSON (JavaScript object notation) in web development circles when talking about data. JSON objects differ slightly from JavaScript objects in that the former has a more strict notation than the latter.
When defining the objects, JSON objects must have "quotation marks" around their properties like such:
1{
2 "property1" : {
3 "property1A" : "value1A"
4 },
5 "property2" : {
6 "property2A" : "value2A",
7 "property2B" : "value2B"
8 },
9 "property3" : "value3"
10}
JSON objects are also not assigned to a variable but sit alone in their own file, with a special .json
file extension!
To handle JSON objects in JavaScript, we would use a special object variable called JSON
(all uppercase letters). Two of the most popular built-in methods of this special object include:
JSON.parse()
JSON.stringify()
JSON.parse()
This converts a JSON string into a JavaScript object:
1// this is a JSON object formatted as a JavaScript string
2const JSONString = '{ "name": "Jon", "age": 100 }'
3
4// that string becomes an object after JSON.parse()
5const parsedObject = JSON.parse(JSONString)
6
The parsedObject
variable becomes a JavaScript object:
1{
2 name: "Jon",
3 age: 100
4}
JSON.stringify()
This converts a JavaScript object into a JavaScript string:
1const user = {
2 name: "Jon",
3 age: 100
4}
5
6const jsonString = JSON.stringify(user)
The jsonString
variable becomes a JavaScript string, ready to be interpreted as JSON object:
1'{"name":"Jon","age":100}'
JavaScript and JSON
As we can see from the two methods above, there is still a translation process between JavaScript and JSON, as the two have "similar but different" notations!