Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through an object by using the .forEach() method and store the result in a new array

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);
    }
});
like image 483
Cody Dillman Avatar asked Dec 05 '25 04:12

Cody Dillman


2 Answers

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);
    }
});
like image 119
NiftyAsp Avatar answered Dec 07 '25 18:12

NiftyAsp


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);
like image 38
Nina Scholz Avatar answered Dec 07 '25 20:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!