Search code examples
javascriptfor-in-loop

get value out of an object using a for in loop in javascript


I'm a JS newbie and am struggling to understand how to get the value out of an object when using a for in loop. Could you all share your knowledge with me please. Thanks!

Here's my problem, the code below just logs the properties and I'm trying to use a for-in loop to find if an object contains the value "apple"

var mac = {
    company: 'apple',
    product: 'iPhone',
    price: 300
};

for (var key in mac) {
  console.log(key);
}

Solution

  • Try this:

    for (var key in mac) {
      if (mac[key] === 'apple'){
        console.log('Contains apple');
      }
    }