.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'
});

So, if I'm interpreting your logic correctly, what you're trying to do is loop through the keys in your defaults object, and if the object you're inspecting doesn't have that key, you want to add that key to the object and assign its value to the default value, is that correct? Any limitations on browser level?

The quickest way to do it if you know for sure what the default data object looks like would be to use a for..in loop:

var data = {}; // or wherever you get it from)
for (var key in defaultData){
   data[key] = data[key] || defaultData[key];
}

That assumes that data.key is non-null and non-false. If false or null is a valid value (and your default is not null or false), then you'll want to make a bit more effort at ascertaining the existence of the key and type of the value. But based on your example, you're not worried about that.


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.

链接地址: http://www.djcxy.com/p/27672.html

上一篇: 与vanilla JS语法相比,Lodash / Underscore语法的组合优势

下一篇: 。每个香草循环