Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing underscore or lodash _.each with vanilla for loop

I'm wanting to replace the following code to no longer rely on the _.each() function of underscore.js or lodash.js:

function fset(data) {
    _.each(dataDefault, function(item, key) {
        var val = ( data[key] ? data[key] : dataDefault[key] );
        $rootScope.meta[key] = val;
    });
};

Ideally, I want to use a vanilla JavaScript for loop, but I don't understand how the _.each() function in underscore/lodash works to replace it...

Something like:

for(var i=0; i<data.length;i++) {
    var val = ( data[key] ? data[key] : dataDefault[key] );
    $rootScope.meta[key] = val;
}

But, I don't know how to get the key and item in this way...

dataDefault looks like:

var dataDefault = {
    title: null,
    description: null
};

An example of calling the function would be:

meta.fset({
    title: 'Hello world',
    description: 'DESC'
});
like image 998
Cameron Avatar asked Sep 29 '22 19:09

Cameron


1 Answers

Try this:

Object.keys(dataDefault).forEach(function (key) { 
    var value = dataDefault[key]
    // iteration code
})

With for..in you have to use hasOwnProperty to exclude inherit properties.

like image 119
Roman Pushkin Avatar answered Oct 03 '22 09:10

Roman Pushkin