More on objects in JS

for...in statement

for...in statement

Overview

The for...in statement iterates over all enumerable properties of an object, including inherited enumerable properties.
Do not confuse it with for...of statement, which is mainly used to loop over arrays.

Simple example


			let obj = {a:1, b:2};
			for(const key in obj){
				console.log(`${key} - ${obj[key]}`);
			}
		

for...in iterates over inherited properties


			const Person = function (name, age) {
				this.name = name;
				this.age = age;
			}

			Person.prototype.greet = function () {
				console.log(`Hello, I.m ${this.name} and I'm ${this.age} years old`);
			}

			let pesho = new Person('Pesho', 23);
			// pesho.greet();

			for(const key in pesho){
				console.log(`${key} - ${pesho[key]}`);
			}

			// name - Pesho
			// age - 23
			// greet - function
		

Make for...in to iterate over own properties only


			const Person = function (name, age) {
				this.name = name;
				this.age = age;
			}

			Person.prototype.greet = function () {
				console.log(`Hello, I.m ${this.name} and I'm ${this.age} years old`);
			}

			let pesho = new Person('Pesho', 23);
			// pesho.greet();

			for(const key in pesho){
				if(pesho.hasOwnProperty(key)){
					console.log(`${key} - ${pesho[key]}`);
				}
			}

			// name - Pesho
			// age - 23
		

Do not confuse for...in with for...of


			let obj = {a:1, b:2};
			for(const key of obj){
				console.log(`key: ${key}`);
			}

			// TypeError: obj is not iterable
		

Object.keys, Object.values, Object.entries

Object.keys, Object.values, Object.entries

Overview

Object.keys(obj) - return an array of obj properties names
Object.value(obj) - return an array of obj properties values
Object.entries(obj) - return an array of arrays. Each inner array has two item. The first item is the property name; the second item is the value.

Simple Example


			let obj = { a:1, b:2 };

			let keys = Object.keys(obj);
			let values = Object.values(obj);
			let entries = Object.entries(obj);

			console.log("keys:", keys);
			console.log("values:", values);
			console.log("entries:", entries);

			// keys: [ 'a', 'b' ]
			// values: [ 1, 2 ]
			// entries: [ [ 'a', 1 ], [ 'b', 2 ] ]
		

Loop through object with Object.keys - example


			let obj = { a:1, b:2 };

			// get the keys as array:
			let keys = Object.keys(obj);

			// loop through keys array:
			for(const key of keys){
				console.log(`${key} - ${obj[key]}`);
			}

			// a - 1
			// b - 2
		

Loop through object with Object.entries - example


			let obj = { a:1, b:2 };

			let entries = Object.entries(obj);

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

			// a - 1
			// b - 2
		

These slides are based on

customised version of

Hakimel's reveal.js

framework