Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  158] [ 7]  / answers: 1 / hits: 19015  / 4 Years ago, tue, october 6, 2020, 12:00:00

how can I push keys and values in an empty object?


You are provided with an array, possibleIterable. Using a for loop, build out the object divByThree so that each key is an element of possibleIterable that is divisible by three. The value of each key should be the array index at which that key can be found in possibleIterable.


const possibleIterable = [4, 3, 9, 6, 23];
const divByThree = {};
// ADD CODE HERE
for (let i =0 ; i < possibleIterable.length; i++)
{
if (possibleIterable[i] % 3 === 0)
{
// ADD CODE HERE!

}
}
console.log(divByThree)

More From » arrays

 Answers
77

You cannot push on to an object. You have to specify the key and value like so:


Literally


divByThree.key = value

Note, in the above example, key is the literal key name, and so you would access it like:


divByThree.key
divByThree['key'] // note the quotes around key

Dynamically


If you want to create a dynamic key based on a js variable for example, you can do:


const keyName = 'myKey';
divByThree[keyName] = value;

To access the value, you can do:


divByThree[keyName];  // no quotes. Value of keyName variable
divByThree['myKey'];
divByThree.myKey;

[#50614] Tuesday, September 22, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nathanaelzechariahl

Total Points: 745
Total Questions: 86
Total Answers: 103

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;