Javascript Objects Cheatsheet

·

4 min read

All about working with objects in one place

Here is a Javascript Object

    let fridge =  {
        make: "Beko",
        model: "224",
        contents:{
            vegetables: {
                favourite: 'lettuce',
                crunchy: 'carrot',
                smallest: 'radish'
            }
        }
    }

Javascript Object vs JSON Object

You can tell that it is a Javascript Object and not a JSON object because the keys are not wrapped in quotes. For instance a JSON object key would look like this; "make".

So we have a Javascript variable called fridge that is a Javascript Object with various properties.

When you want to loop through an Object here are your options;

  1. ''for in'' loop
  2. convert the Object to an array using eg Object.keys then use eg forEach
  3. convert the Object to an array using eg Object.values then use eg forEach
  4. convert the Object to an array of arrays using Object.entries then use eg forEach
  5. convert the Object to an array and then use ''for of'' loop

For in loop

For in is the original older type loop that came in early to JS. For in loops can be used to loop over the enumerable properties of an Object,Array or String...we will get into more detail later.

First let's use a ''for in'' loop to get this object's keys and values;'

for (const key in fridge) {

    console.log(`${key}: ${fridge[key]}`);
}

//make: Beko
//model: 224
//contents: [object Object]

Where does the key fit in?

The fridge[key] part of this used to puzzle me, until I read about associative arrays in the MDN documents, now I think of each property as a mini-array of two things, a key and a value, when I want the value of a property I can access it with the [key], , eg fridge['make']the same way you would access an item in an array with an index eg array[2]

.... more about enumerable properties........

for..in is a method for iterating over "enumerable" properties of an object. It therefore applies to all objects not only Object type objects, but also Array type Objects and even Strings eg

const array = ['a', 'b', 'c', 'd'];

for (const index in array) {
    console.log(array[index])
}
//a,b,c,d

for..in and Strings

Each character in a string has an index. Therefore, similar to Arrays, the indexes are enumerable properties that just happen to be integers. more details here bitsofco.de/for-in-vs-for-of

const string = 'Ire Aderinokun';

for (const index in string) {
    console.log(string[index])
}

// Result: I, r, e, , A, d, e, r, i, n, o, k, u, n

Moving on lets look at directly accessing a property in an object with dot notation

Dot and bracket notation

If you already know the key of the property you can get the value with dot notation, eg fridge.make would return ''Beko'', you can also use bracket notation to do the same thing eg fridge['make'] would return ''Beko'' (note the quotation marks within the brackets).

Instead of for in loop

Before ES6, the only way to loop through an object was by using the for...in loop. The problem with using the for...in method is that it loops through the properties in the prototype chain as well. To avoid this problem, you have to explicitly check if the property belongs to the object by using the hasOwnProperty() method.

Object.keys()

The Object.keys() method was introduced in ES6 to make it easier to loop over objects. It extracts the keys into an array. You can forEach loop over the array of keys using each key to access the corresponding property within the object.

const keys = Object.keys(fridge);
console.log(keys)// ["make", "model", "contents"]
keys.forEach((key, index) => {
    console.log(`${key}: ${fridge[key]}`);
});
//make: Beko
//model: 224
//contents: [object Object]

Object.values()

returns an array of the values

let values = Object.values(fridge).forEach(val => console.log(val))
//Beko
//224
//{vegetables: {crunchy: "carrot", favourite: "lettuce", smallest: "radish"}}

And see, instead of Object object we have all the vegetables - and in alphabetic order too.

Object.entries() (ES8 )

Outputs an array of arrays. Each inner array has two elements. The first element being the property and the second element is the value.

Object.entries(fridge) =
//  [ 
//      ["make", "Beko"],
//      ["model", "224"],
//      ["contents", {…}]  
//   ]

You can now loop over these array using array methods, eg forEach() map etc

Object.entries(fridge).forEach(([key, value]) => {
    console.log(`${key}: ${value}`)
});
//make: Beko
//model: 224
//contents: [object Object]

...you can get this same result by using the for of loop. for..of is a method, introduced in ES2015, for iterating over "iterable collections", Objects are not iterable collections, but Arrays are. Take away - you can only use for of with arrays - not Objects.

for (const [key, value] of Object.entries(fridge)) {
    console.log(`${key}: ${value}`);
}

Remember you can not use ''for of'' directly on an Object. Your choices are

  1. ''for in''
  2. convert the Object to an array using eg Object.keys then use eg forEach
  3. convert the Object to an array using eg Object.values then use eg forEach
  4. convert the Object to an array of arrays using Object.entries then use eg forEach
  5. convert the Object to an array and then use ''for of'' loop

That's it for now.