Filling Objects via Loop in JavaScript
Objects can also be filled with data in loops. Let's look at an example. Suppose we have two arrays:
let keys = ['a', 'b', 'c', 'd', 'e'];
let values = [1, 2, 3, 4, 5];
Let's use them to create an object, taking the keys for this object from the first array, and the values - from the second one. To do this, let's run a loop and within the loop we will form our object:
let obj = {};
for (let i = 0; i <= 4; i++) {
let key = keys[i];
let value = values[i];
obj[key] = value;
}
console.log(obj);
It is not necessary to introduce variables for the key and value, you can simply do it like this:
let obj = {};
for (let i = 0; i <= 4; i++) {
obj[keys[i]] = values[i];
}
console.log(obj);
Given two arrays: the first with the names of the days of the week, and the second - with their serial numbers:
let arr1 = ['a', 'b', 'c', 'd', 'e'];
let arr2 = [1, 2, 3, 4, 5];
Using a loop, create an object whose keys will be the names of the days, and the values will be their numbers.
Given an object:
let obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
Iterate over this object with a loop and write into a new object those elements which are even numbers.
Given an object:
let obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
Iterate over this object with a loop and create a new object so that its keys become the elements of the old object, and the values become the keys of the old object.