Objects can also be filled with data in loops. Let's look at an example. Let's say we have two arrays:
let keys = ['a', 'b', 'c', 'd', 'e'];
let values = [1, 2, 3, 4, 5];
Let's use them to make an object by taking the keys for this object from the first array, and the values from the second. To do this, we will start the loop and in 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 enter variables for the key and value, you can just do this:
let obj = {};
for (let i = 0; i <= 4; i++) {
obj[keys[i]] = values[i];
}
console.log(obj);
Two arrays are given: the first with the names of the days of the week, and the second with their ordinal numbers:
let arr1 = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
let arr2 = [1, 2, 3, 4, 5, 6, 7];
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};
Loop through this object and write to the new object those elements that are even numbers.
Given an object:
let obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
Iterate over this object and create a new object so that its keys are the elements of the old object and its values are the keys of the old object.