ShakaCode | ShakaCode Blog | Rails On Maui Blog | Rails | ReactJs | JavaScript | Webpack | Productivity |

Iterating over properties (not values) of JavaScript Object


#1

Here’s iteration of an object’s own keys in ES6.

References:

const obj = { a: 1, b:1};
obj.__proto__.x = 1;

console.log("With Object.keys");

for (let k of Object.keys(obj)) {
  console.log(`k is ${k}`);
}

console.log("Without Object.keys, we get prototype");

for (let k in obj) {
  console.log(`k is ${k}`);
}

console.log("Without Object.keys, checking hasOwnProperty");

for (let k in obj) {
  if (obj.hasOwnProperty(k)) {
    console.log(`k is ${k}`);
  }
}

#2

If using lodash:

_.forOwn(obj, function(v, k) {
  console.log(k); //logs a,b
});

_.forIn(obj, function(v, k) {
  console.log(k); //logs a,b,x
});

Fiddle


#3

Here’s a couple pictures:


#4

ES6 — definitely FTW :rocket:


#5

And ES7

https://babeljs.io/docs/usage/experimental/

:+1:


#6

Someone needs to read https://leanpub.com/exploring-es6/ and blogs by Alex Rauschmayer.