JavaScript objects and JSON

collecting properties and values into containers
// 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:

// the simplest object has an empty set of curly braces
const emptyObject = {}

// the simplest non-empty object has a key and some value
const oneKeyObject = {
    name: "Jon"
}

// objects can have properties which hold values of any data type: 
const complexObject = {
    key1 : "Hello",
    key2 : "Hey", 
    anotherKey : 42, 
    someOtherKey : true, 
    nestedObject : { 
        nestedObjectKey: true
    },
    method: function() {
        return "Surprise!"
    }
}

// example of an object used "in real life": 
const person = {
    name : "Jon", 
    age : 100, 
    retired : false, 
    hobbies : ["travel", "languages", "sports"], 
    getAge : function() {
        return this.age
    }
}

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)

More abstractly, an object would look like:

let value1 = "value1's value"

keyword objectVariableName {
  // assigning a variable
  keyName1 : value1, 
  // assigning a string
  keyName2 : "value2", 
  ...
}

Some restrictions in JavaScript:

  • the keyword would be either const, let or var
  • 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"
const object = {
  "multi-word key" : "some value"
}

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:

console.log(objectVariableName.keyName1)
// "value1's value"

console.log(objectVariableName.keyName2)
// "value2"

console.log(objectVariableName["multi-word key"])
// "some value"

Nested objects

We can even have objects within objects:

const person = {
    name: {
        first: "Mark",
        middle: "James", 
        last: "Park"
    },
    phone: {
        personal: {
            land: '555-111-1234'
            mobile: '555-999-8875'
        },
        work: {
            land: '000-000-0000'
        }
    } 
}  

console.log(person.name.last)
// Park  

console.log(person["name"]["last"])
// Park

console.log(person["phone"]["personal"]["land"])
// '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:

const complexObject = {
  key1 : "Hi", 
  key2 : {
    key2a : "2A",
    key2b : "2B"
  }
}

const { key2 : { key2a }} = complexObject
console.log(key2a)
// 2A

const { key2 : { key2a, key2b }} = complexObject
console.log(key2a, key2b)
// 2A 2B

Removing object properties

For whatever reason, we can use the unary operator delete to remove an object's property:

const simpleObject = { 
  key1 : "Hi",
  key2 : 100,
  key3 : false
}

delete simpleObject.key2

console.log(simpleObject.key2)
// undefined

console.log(simpleObject)
// { 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():

const simpleObject = { 
  key1 : "Hi",
  key2 : 100,
  key3 : false,
  key4 : null
}

console.log(simpleObject.hasOwnProperty("key1"))
// true

console.log(simpleObject.hasOwnProperty("key5"))
// false

We can also use the in operator if hasOwnProperty takes too long to type:

const simpleObject = { 
  key1 : "Hi",
  key2 : 100,
  key3 : false,
  key4 : null
}

console.log("key1" in simpleObject)
// true

console.log("key5" in simpleObject)
// 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:

const simpleObject = { 
  key1 : "Hi",
  key2 : 100,
  key3 : false,
  key4 : null
}

console.log(simpleObject.key5?.name)
// undefined

console.log(simpleObject?.key5)
// 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:

const myObject = { 
  firstName: "Jon", 
  lastName: "Coded", 
  age: 100 
}

for (let key in myObject) {
  console.log(key + ": " + myObject[key])
}

/* Output: 
firstName: Jon 
lastName: Coded
age: 100

Breaking that down:

  • we let key (the first variable) represent each property name of myObject
  • then we use in to reference myObject
  • 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:

{ 
  "property1" : { 
    "property1A" : "value1A" 
  }, 
  "property2" : { 
    "property2A" : "value2A", 
    "property2B" : "value2B" 
  }, 
  "property3" : "value3" 
}

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:

// this is a JSON object formatted as a JavaScript string
const JSONString = '{ "name": "Jon", "age": 100 }'

// that string becomes an object after JSON.parse()
const parsedObject = JSON.parse(JSONString)

The parsedObject variable becomes a JavaScript object:

{
  name: "Jon",
  age: 100
}

JSON.stringify()

This converts a JavaScript object into a JavaScript string:

const user = {
  name: "Jon",
  age: 100
}

const jsonString = JSON.stringify(user)

The jsonString variable becomes a JavaScript string, ready to be interpreted as JSON object:

'{"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!

⬅️ older (in textbook-javascript)
📒 JavaScript functions
newer (in textbook-javascript) ➡️
JavaScript arrays 📒
⬅️ older (in code)
📒 JavaScript functions
newer (in code) ➡️
JavaScript arrays 📒
⬅️ older (posts)
📒 JavaScript functions
newer (posts) ➡️
JavaScript arrays 📒