Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call all functions inside an object in javascript? [duplicate]

var imgs = {
    a: function(){
        //...
    },
    b: function(){
        //...
    },
    c: function(){
        //...
    }
};
var preloadImgs = function(){
    imgs.a();
    imgs.b();
    imgs.c();
};
preloadImgs();

Is there a way to automate preloadImgs so it loads all the methods inside imgs at once, instead of me having to type every single one?

like image 363
Magdi Gamal Avatar asked Sep 18 '25 07:09

Magdi Gamal


1 Answers

Use Object.values

Object.values( imgs ).forEach( s => s() );

Demo

var imgs = {
    a: function(){
       console.log("1");
    },
    b: function(){
       console.log("2");
    },
    c: function(){
       console.log("3");
    }
};
var preloadImgs = function(){
    Object.values( imgs ).forEach( s => s() );
};
preloadImgs();

Edit

If all the values in imgs are not function, then you can apply the filter first

Object.values( imgs )
  .filter( s => typeof s === 'function' ) //filter out values which are function
  .forEach( s => s() ); //execute those functions
like image 58
gurvinder372 Avatar answered Sep 19 '25 19:09

gurvinder372