How to set all values of an object to null in JavaScript?

Here’s a useful function called ‘Object.keys()’, it returns all of the attribute names of an object.

let setAll = (obj, val) => Object.keys(obj).forEach(k => obj[k] = val);
let setNull = obj => setAll(obj, null);

Non-arrow-function version:

function setAll(obj, val) {
    /* Duplicated with @Maksim Kalmykov
        for(index in obj) if(obj.hasOwnProperty(index))
            obj[index] = val;
    */
    Object.keys(obj).forEach(function(index) {
        obj[index] = val
    });
}
function setNull(obj) {
    setAll(obj, null);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)