Adag89
Adag89

Reputation: 161

How to use an If statement within a for-in loop?

Just trying to get more comfortable with nested objects in arrays, and for in loops. Everything works as I expect it to, until I insert an if statement, then I don't get my expected results of an output of true in the console.

I have tried various mixes of dot/bracket notations for access.

const animals = [
  {
    species: 'Pets',
    list: [
      'Dog',
      'Cat',
      'Rabbit',
      'Gerbil',
      'Turtle',
      'Canary'
    ]
  },
  {
    species: 'Wild',
    list: [
      'Bear',
      'Lion',
      'Deer',
      'Tiger',
      'Cougar',
      'Elk',
      'Beaver',
      'Elephant',
      'Rhino'
    ]
  },
  {
    species: 'Marine',
    list: [
      'Shark',
      'Salmon',
      'Squid',
      'Octopus',
      'Jellyfish'
    ]
  }
];

for(let i = 0; i < animals.length; i++) {
  for(let prop in animals[i]) {
    console.log(animals[i][prop])
    if(animals[i][prop] === 'Shark'){
       console.log(true)
    }
  }
}

I would like to console log true, if the value equals "Shark"

Upvotes: 3

Views: 872

Answers (5)

Ahmed Ahmed
Ahmed Ahmed

Reputation: 1056

you can use the code below

animals.flatMap(a=> a.list).filter(a=> a==='Shark').forEach(a=> console.log('true'))

Upvotes: 1

Andy Hoffman
Andy Hoffman

Reputation: 19111

I want to add a functional approach to the possible solutions:

const animals = [{ species: 'Pets', list: ['Dog', 'Cat', 'Rabbit', 'Gerbil', 'Turtle', 'Canary'] }, { species: 'Wild', list: ['Bear', 'Lion', 'Deer', 'Tiger', 'Cougar', 'Elk', 'Beaver', 'Elephant', 'Rhino' ] }, { species: 'Marine', list: ['Shark', 'Salmon', 'Squid', 'Octopus', 'Jellyfish'] }];

const searchQuery = 'Shark';

function fishForSharks(animal) {
  return animal.list.includes(searchQuery);
}

function getKeyPositionFromValue(obj) {
  return Object.keys(obj.list).find(key => obj.list[key] === searchQuery);
}

function output(obj) {
  const output = document.querySelector('.output');

  output.innerHTML += `
  <li>
The <strong>${obj.species}</strong> species 
contains a ${searchQuery} at position: 
${getKeyPositionFromValue(obj)}
  </li>`;
}

animals.filter(fishForSharks).map(output);
<ul class="output"></ul>

http://jsfiddle.net/ujf1t2p0/

Upvotes: 0

Tom O.
Tom O.

Reputation: 5941

Here is an approach that utilizes Array.prototype.forEach and ES6 object destructuring:

const animals = [{
    species: 'Pets',
    list: [
      'Dog',
      'Cat',
      'Rabbit',
      'Gerbil',
      'Turtle',
      'Canary'
    ]
  },
  {
    species: 'Wild',
    list: [
      'Bear',
      'Lion',
      'Deer',
      'Tiger',
      'Cougar',
      'Elk',
      'Beaver',
      'Elephant',
      'Rhino'
    ]
  },
  {
    species: 'Marine',
    list: [
      'Shark',
      'Salmon',
      'Squid',
      'Octopus',
      'Jellyfish'
    ]
  }
];

animals.forEach(function(el) {
  var {
    species,
    list
  } = el;

  list.forEach(function(s) {
    if (s === 'Shark') {
      console.log('Found shark');
    }
  })
});

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You need to iterate the array as well

const animals = [{ species: 'Pets', list: ['Dog', 'Cat', 'Rabbit', 'Gerbil', 'Turtle', 'Canary'] }, { species: 'Wild', list: ['Bear', 'Lion', 'Deer', 'Tiger', 'Cougar', 'Elk', 'Beaver', 'Elephant', 'Rhino' ] }, { species: 'Marine', list: ['Shark', 'Salmon', 'Squid', 'Octopus', 'Jellyfish'] }]

for (let i = 0; i < animals.length; i++) {
    for (let prop in animals[i]) {
        // console.log(animals[i][prop]);
        for (var item of animals[i][prop]) {
            if (item === 'Shark') {
                console.log(true);
            }
        }
    }
}

A shorter approach would be to iterate animals and then list.

const animals = [{ species: 'Pets', list: ['Dog', 'Cat', 'Rabbit', 'Gerbil', 'Turtle', 'Canary'] }, { species: 'Wild', list: ['Bear', 'Lion', 'Deer', 'Tiger', 'Cougar', 'Elk', 'Beaver', 'Elephant', 'Rhino' ] }, { species: 'Marine', list: ['Shark', 'Salmon', 'Squid', 'Octopus', 'Jellyfish'] }]

animals.forEach(({ list }) => {
    if (list.includes('Shark')) {
        console.log(true);
    }
});

Upvotes: 3

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result , use includes

animals[i][prop].includes('Shark')

Issue: animals[i][prop] in your code returns each object property and value- Shark is one of the array element

Please find the working code below

const animals = [
{
    species: 'Pets',
    list: [
        'Dog',
        'Cat',
        'Rabbit',
        'Gerbil',
        'Turtle',
        'Canary'
    ]

},
 {
     species: 'Wild',
     list: [
         'Bear',
         'Lion',
         'Deer',
         'Tiger',
         'Cougar',
         'Elk',
         'Beaver',
         'Elephant',
         'Rhino'
     ]
 },
  {
      species: 'Marine',
      list: [
          'Shark',
          'Salmon',
          'Squid',
          'Octopus',
          'Jellyfish'
      ]
 }

]

for(let i = 0; i < animals.length; i++) {
for(let prop in animals[i]) {
    console.log(animals[i][prop])
   console.log(animals[i][prop].includes('Shark'))

}
}

Upvotes: 1

Related Questions