Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES5: Object.keys native method in JS

Tags:

javascript

I am using Object.keys to iterate through an object's keys in JS like so:

               var cv = view.childViews;

                Object.keys(cv).forEach(function(key) {
                    this.destroyView(cv[key]);
                }.bind(this));

however, when cv is undefined or is not an object, Object.keys throws an error. Instead of putting an if statement around Object.keys to check if the typeof cv is an object, is there a native method that is better than Object.keys in that it doesn't throw an error if cv is undefined?

Isn't the whole point of:

Object.keys(cv) vs cv.keys().each()

if cv is null, the first shouldn't throw an error, whereas the latter should. What the heck, thanks JS.

If you don't help me, I will being doing this, much to my own chagrin:

              if(typeof cv === 'object'){
                    Object.keys(cv).forEach(function(key) {
                        this.destroyView(cv[key]);
                    }.bind(this));
                }

turns out, in ES6, non-object arguments to Object.keys will be "coerced" into an object, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

like image 336
Alexander Mills Avatar asked Mar 16 '23 09:03

Alexander Mills


2 Answers

If you're just iterating, there's good old for...in

for(var i in null){
  alert(i);
}

for(var i in undefined){
  alert(i);
}

var obj = {hello: 'world'};

for(var i in obj){
  alert(i);
  alert(obj[i]);
}
like image 154
Chad Hedgcock Avatar answered Mar 18 '23 00:03

Chad Hedgcock


I think @Pointy has the right answer so I'll put it here:

Object.keys(cv || {}).forEach(...)

Basically, if cv is undefined then use a dummy object and do nothing.

One other tactic would be just to do the same in the var:

var cv = view.childViews || {};
like image 43
beautifulcoder Avatar answered Mar 18 '23 00:03

beautifulcoder