Reputation: 1
I'm trying to figure out the following challenge:
Write a script in a programming language of your choice (I'm going with vanilla JS) that uses a loop and a conditional statement to find the value of the number of dogs in the following collection of key-value pairs. Depending on what language you’re using, it is acceptable to think of this variable as either a dictionary or an array of key-value pairs. Please only use logic that is native to the language without any external libraries:
KennelCapacity = {cats: 7, hamsters: 12, birds: 21, dogs: 3, chickens: 1}
I'm trying to set up a for loop with an if/else statement, but I'm honestly not sure how to piece it together for a proper answer. How should I do this?
Upvotes: 0
Views: 306
Reputation: 704
So, this question is very strange, because in JavaScript you could just do KennelCapacity.dogs
and get the number of the dogs.
But this is not the question, so the following would be a possible solution:
const KennelCapacity = {
cats: 7,
hamsters: 12,
birds: 21,
dogs: 3,
chickens: 1
};
let numberOfDogs;
// this gets [key, value] (here [animal, number]) of each key-value pair in the object
for (let [animal, number] of Object.entries(KennelCapacity)) {
if (animal == "dogs") {
numberOfDogs = number;
break;
}
}
console.log(numberOfDogs);
This code runs through your Object and gets each value-pair. (See Object.entries() at MDN).
With the Javascript notation [key, value]
you can split the given array in the key and value or in my example code animal
and value
.
In the if statement is checked if the key is "dogs"
. If that is true, numberOfDogs
is set to the number of dogs, that is stored as value in your object and the for loop is broken.
I hope, this helps you. If you have more questions, you are welcome to ask.
Upvotes: 1