Question

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);
}
Was it helpful?

Solution

Try this:

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

OTHER TIPS

It should be

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

Solution 1

As your question says, if all you wanted to do is to check if apple is one of the values of the object, you can use Array.some and Object.keys method like this

var foundApple = Object.keys(mac).some(function(key) {
    return mac[key] === "apple";
});
console.log(foundApple);

Note: Both those functions are pretty additions to the language, so you might want to check the compatibility, before you use them.

  1. Compatibility table for Array.some
  2. Compatibility table for Object.keys

Solution 2:

If you are looking for a solution which is compatible with all the common browsers, you can do like this

var foundApple = false;
for (var key in mac) {
    foundApple = (mac[key] === "apple");
    if (foundApple) break;
}

I wanted a take a moment to throw my own answer in here. I was looking this up earlier and I found an answer real quick. I'll try to explain in the event anyone else has a hard time with this concept in general (i.e. usually newer folks).

Overview

In vanilla Javascript/ECMAscript you can loop through either arrays or objects using the for loop constructor. The format of the for loop just depends on what you're looping over: Array or Object.

Read more about for loops in general here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

For loops with Objects

The syntax of a for loop is a bit different than an array and is commonly referred to as a "for in" loop.

You can read more about "for in" looping in Javascript here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Here's the syntax:

for( key in object) {
  console.log(key); // this logs the key name in the loop to the console
  console.log(object[key]) // this logs the key value in the loop to the console
}

Breaking down what's happening above:

key is just a generic variable that represents the object's keys in the loop. This can be anything you want:

for( someBullShit in object) {
  console.log(someBullShit); 
  console.log(object[someBullShit]);
}

This loop would have the same output as the previous example.

Accessing Object Values in a "for in" loop

As stated in the above example, you can access the value of an object key in a "for in" loop exactly like you normally would, except you'll use your "key variable" in place of the actual key name.

Example:

object[keyname] // this represents the value of a given key

I've also included extra info below in case someone finds it useful:

For Loops with Arrays

The format for a "standard" for loop is simple:

for ([initialization]; [condition]; [final-expression]) statement

In simple terms:

Initialization - Set a starting point (which for counting purposes in Javascript would be an index of 0.

Example:

var array = [1,2,3,4,5];

for(var i = 0; [condition]; [final-expression]) {
   ...
}

This means the loop starts counting at 0

Condition - This sets when the loop stops. 99.9% of time you're going to tell your loop to end when it successfully loops through each item once.

Example:

var array = [1,2,3,4,5];

for([initialization]; i < array.length ; [final-expression]) {
   ...
}

This means that the loop should run as long as the number of times the loop has run is less than the length of the array.

Final Expression - Here you are telling your loop what to do after the loop finishes (i.e. after you successfully loop through each item in the array, do this). 99.9% of the time this will be an increment to the index so the index's value increases by 1 each time the loop runs (just like counting off on your hand).

Example:

var array = [1,2,3,4,5];

for([initialization]; [condition]; i++) {
   ...
}

The final expression value there just says increase the value of this variable by 1.

   for (let [key, value] of Object.entries(object_name)) {
     console.log(key +" : " + value + "\n");
} 

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well) check mozilla developer network for more details

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top