Skip to content

JavaScript ES6: How to Iterate Over Object with [Symbol()] names

I’m trying to figure out how to iterate over an object that is using Symbol names to uniquely identify properties. For instance, if I have this object:

   const bowl1 = {
     'apple': { color: 'red', weight: 136.078 },
     'banana': { color: 'yellow', weight: 183.151 },
     'orange': { color: 'orange', weight: 170.097 },
     'peach': { color: 'yellow', weight: 176.845 }
   };
   for (var fruit in bowl1) {
       var item = bowl1[fruit];
       console.log(`${fruit}: `, item);
   }
   OUTPUT:
   apple:  { color: 'red', weight: 136.078 }
   banana:  { color: 'yellow', weight: 183.151 }
   orange:  { color: 'orange', weight: 170.097 }
   peach:  { color: 'yellow', weight: 176.845 }
   // can even write your own iterator to get the same results
   function* iterate_object(o) {
      var keys = Object.keys(o);
      for (var i = 0; i < keys.length; i++) {
         yield [keys[i], o[keys[i]]];
      }
   }
   // output is the same as above
   for (var [key, val] of iterate_object(bowl1)) {
      console.log(key, val);
   }

However, if I change this object to use Symbols as such:

   const bowl = {
     [Symbol('apple')]: { color: 'red', weight: 136.078 },
     [Symbol('banana')]: { color: 'yellow', weight: 183.15 },
     [Symbol('orange')]: { color: 'orange', weight: 170.097 },
     [Symbol('banana')]: { color: 'yellow', weight: 176.845 }
   };

Note that symbols are used to keep the second banana from overwriting the first.

Anyway, neither method used above will iterate properly over this object.

Is there a way to iterate over objects using Symbol names? Does it need to be created as a class and have an iterator method?

Thanks in advance for the help.

Answer

You can’t get symbol property names because they’re not stored as typical character/string values, but you can iterate over the list returned by Object.getOwnPropertySymbols and use those to pull information out of an Object.

const bowl = {
     [Symbol('apple')]: { color: 'red', weight: 136.078 },
     [Symbol('banana')]: { color: 'yellow', weight: 183.15 },
     [Symbol('orange')]: { color: 'orange', weight: 170.097 },
     [Symbol('banana')]: { color: 'yellow', weight: 176.845 }
   };
for(let sym of Object.getOwnPropertySymbols(bowl) ) {
   console.log(bowl[sym]);
}