Having created a simple function to retrieve certain values from an array that contains multiple nested objects, I am facing a dilemma with my loops.
My query pertains to the necessity of looping through the 3 objects before accessing their values. While I understand the need for initially looping through the entire array, I am puzzled as to why a separate loop is required for each object.
Instead of running two loops, can't I use the following code snippet to access the desired value:
animalNoises[i][animal][country]
Unfortunately, this line of code returns 'undefined' for me. Could this issue be related to the structure of the 3 animal objects?
I appreciate any assistance in this matter and am grateful for the support from the Stack Overflow community.
function petSounds(animal, country) {
let phrase = ''
for (let i = 0; i < animalNoises.length; i++) {
for (let key in animalNoises[i]){
if (animal === key){
let sound = animalNoises[i][key][country];
phrase = animal + 's' + ' in ' + country + ' say ' + sound
}
}
}
return phrase
}
let animalNoises = [
{ 'dog': {
'America' : 'Woof! Woof!',
'Germany' : 'Wau Wau!',
'England' : 'Bow wow!',
'Uruguay' : 'Jua jua!',
'Afrikaans' : 'Blaf!',
'Korea' : 'Mong mong!',
'Iceland' : 'Voff voff!',
'Albania' : 'Ham!',
'Algeria' : 'Ouaf ouaf!'
}
},
{ 'cat': {
'America' : 'Meow',
'Germany' : 'Miauw!',
'England' : 'mew mew',
'Uruguay' : 'Miau Miau!',
'Afrikaans' : 'Purr',
'Korea' : 'Nyaong!',
'Iceland' : 'Kurnau!',
'Albania' : 'Miau',
'Algeria' : 'Miaou!'
}
},
{ 'chicken': {
'America' : 'Cluck cluck',
'Germany' : 'tock tock tock',
'England' : 'Cluck Cluck',
'Uruguay' : 'gut gut gdak',
'Afrikaans' : 'kukeleku',
'Korea' : 'ko-ko-ko',
'Iceland' : 'Chuck-chuck!',
'Albania' : 'Kotkot',
'Algeria' : 'Cotcotcodet'
}
}
];