I want to loop throught the object, dogNames, and return only the names of dogs I own into the array, myDogs. I want myDogs to appear as such when logged:
['Remington','Ruby','Chief','Link']
Most likely, I'm not understanding how the .forEach() method works and/or how to manipulate objects. This is some homework help an I'm just not understanding the .forEach() method after a few hours on this. Thank you for any help. Please just point me in the right direction, I don't want other people to solve this.
First, here is the array I've written.
var dogNames = [
{name: Kevin, mine: false},
{name: Remington, mine: true},
{name: Bingo, mine: false},
{name: Ruger, mine: false},
{name: Ruby, mine: true},
{name: Gino, mine: false},
{name: Chief, mine: true},
{name: Watson, mine: false},
{name: Link, mine: true}
];
This is the array I want to store the result to.
var myDogs = [];
This is what I've attempted to do after some google.
dogNames.forEach(function(mine){
if(mine === true){
myDogs.push(dogNames.name);
}
});
When you iterate through dogNames the argument in function is each object. So what you think is mine is actually the entire object.
Instead:
dogNames.forEach(dogName => {
if(dogName.mine === true){
myDogs.push(dogName.name);
}
});
You could filter and the array and map the names of the filtered array.
var dogNames = [{ name: 'Kevin', mine: false }, { name: 'Remington', mine: true }, { name: 'Bingo', mine: false }, { name: 'Ruger', mine: false }, { name: 'Ruby', mine: true }, { name: 'Gino', mine: false }, { name: 'Chief', mine: true }, { name: 'Watson', mine: false }, { name: 'Link', mine: true }],
myDogs = dogNames
.filter(({ mine }) => mine)
.map(({ name }) => name)
console.log(myDogs);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With