Javascript: Object & Loop

This article deals with creating a Javascript object and using different functions on the object. We also see how we can loop through the object and get the values.

Create a new Javascript Object


var myObject = {
	fruit: 'apple',
	flower: 'rose',
	vegetable: 'cabbage'
};

console.log(myObject); 
// {fruit: "apple", flower: "rose", vegetable: "cabbage"}

Access elements of the array


console.log(myObject.fruit); // apple
console.log(myObject.flower); // rose
console.log(myObject.vegetable); // cabbage

Another way of creating/defining object


var myObject = new Object();
myObject.fruit = 'apple';
myObject.flower = 'rose';
myObject.vegetable = 'cabbage';

console.log(myObject); 
// {fruit: "apple", flower: "rose", vegetable: "cabbage"}

Get keys of the object


console.log(Object.keys(myObject)); // ["fruit", "flower", "vegetable"]

Get values of the object


console.log(Object.values(myObject)); // ["apple", "rose", "cabbage"]

Get length/size of the object


console.log(Object.keys(myObject).length); // 3

Change value of any particular key


// change value of 'mango' to 'banana'
myObject.fruit = 'banana';
console.log(myObject.fruit); // banana
console.log(myObject); // {fruit: "banana", flower: "rose", vegetable: "cabbage"}

Add item/property to the object


myObject.drinks = 'juice';
console.log(myObject); // {fruit: "banana", flower: "rose", vegetable: "cabbage", drinks: "juice"}

Remove item/property from the object


delete myObject.drinks;
console.log(myObject); // {fruit: "banana", flower: "rose", vegetable: "cabbage"}

Concatenate or merge multiple objects


// ECMAscript 6 (ES6) introduces Object.assign() method for this
newObject = {drinks: 'coffee'};
var mergedObject = Object.assign(myObject, newObject);
console.log(myObject); // {fruit: "banana", flower: "rose", vegetable: "cabbage", drinks: "coffee"}
console.log(newObject); // {drinks: "coffee"}
console.log(mergedObject); // {fruit: "banana", flower: "rose", vegetable: "cabbage", drinks: "coffee"}

Delete the newly added property


delete myObject.drinks;
console.log(myObject); // // {fruit: "banana", flower: "rose", vegetable: "cabbage"}

Check if the variable is an object


console.log(Object.prototype.toString.call(myObject)); // [object Object]

if (Object.prototype.toString.call(myObject) === '[object Object]') {
    console.log('The variable is an object.');
} else {
	console.log('The variable is NOT an object.');
}

var myArray = [1, 2, 3];
console.log(Object.prototype.toString.call(myArray)); // [object Array]

Using for…in loop


for (key in myObject) {
	console.log(key, myObject[key]);
}
// fruit banana
// flower rose
// vegetable cabbage

Using Object.keys() method to loop through the object


// Object.keys() returns the keys of the object
Object.keys(myObject).forEach(function(key, index) {
	console.log(index, key, myObject[key]);
});
// 0 "fruit" "banana"
// 1 "flower" "rose"
// 2 "vegetable" "cabbage"

Using Object.values() method to loop through the object


If you don't need "keys", then you can use the Object.values() method.

// Object.values() returns the values of the object
Object.values(myObject).forEach(function(value, index) {
	console.log(index, value);
});
// 0 "banana"
// 1 "rose"
// 2 "cabbage"

Using Object.entries() method to loop through the object


// Object.entries() returns the [key, value] pair of the object
console.log(Object.entries(myObject)); 
// [ ["fruit", "banana"], ["flower", "rose"], ["vegetable", "cabbage"] ]

// using Object.entries() method to loop through the object
Object.entries(myObject).forEach(function([key, value], index) {
	console.log(index, key, value);
});
// 0 "fruit" "banana"
// 1 "flower" "rose"
// 2 "vegetable" "cabbage"

Another way of write the above code


Object.entries(myObject).forEach(([key, value], index) => {
	console.log(index, key, value);
});
// 0 "fruit" "banana"
// 1 "flower" "rose"
// 2 "vegetable" "cabbage"

Using for loop with Object.entries() method


for (const [key, value] of Object.entries(myObject)) {
	console.log(key, value);
}
// fruit banana
// flower rose
// vegetable cabbage

Nested object or Multi-dimensional object


var myObjectNested = {
	fruit:     {a: 'apple', b: 'orange', c: 'mango'},
	flower:    {a: 'rose', b: 'lotus', c: 'lily'},
	vegetable: {a: 'cabbage', b: 'carrot', c: 'beans'}
};

console.log(myObjectNested.fruit);
// {a: "apple", b: "orange", c: "mango"}

console.log(myObjectNested.fruit.a); // apple

Nested loop for-each


Object.entries(myObjectNested).forEach(function([key, value], index) {
	Object.entries(value).forEach(function([k, v], idx) {
		console.log(index, idx, key, k, v);
	});
});
// 0 0 "fruit" "a" "apple"
// 0 1 "fruit" "b" "orange"
// 0 2 "fruit" "c" "mango"
// 1 0 "flower" "a" "rose"
// 1 1 "flower" "b" "lotus"
// 1 2 "flower" "c" "lily"
// 2 0 "vegetable" "a" "cabbage"
// 2 1 "vegetable" "b" "carrot"
// 2 2 "vegetable" "c" "beans"

Nested loop for-each using recursive function


function nestedLoop(myObject) {
	Object.entries(myObject).forEach(function([key, value], index) {
		if (value && typeof value === 'object') {
			nestedLoop(value); // recursive call
		} else {
			console.log(key, value); 
		} 
	});
}

nestedLoop(myObject);
nestedLoop(myObjectNested);
// fruit banana
// flower rose
// vegetable cabbage
// a apple
// b orange
// c mango
// a rose
// b lotus
// c lily
// a cabbage
// b carrot
// c beans

Nested loop for-each using recursive function

Here, we use the Arrow function, also called “fat-arrow” function.

It’s a more concise syntax for writing function expressions.

It was introduced in ECMAScript 6 (ES6).

ECMAScript (ES) is a scripting language specification standardized by ECMAScript International.


// ES6 example function code:
// const multiply = (x, y) => { return x * y };
const nestedLoopNew = (myObject) => {
	Object.entries(myObject).forEach(function([key, value], index) {
		if (value && typeof value === 'object') {
			nestedLoopNew(value); // recursive call
		} else {
			console.log(key, value); 
		} 
	});
};

nestedLoopNew(myObject);
nestedLoopNew(myObjectNested);
// fruit banana
// flower rose
// vegetable cabbage
// a apple
// b orange
// c mango
// a rose
// b lotus
// c lily
// a cabbage
// b carrot
// c beans

Hope this helps. Thanks.