Sean
Sean

Reputation: 63

How to modify object property values while enumerating

An API call I'm making returns empty objects in lieu of null. Tedious doesn't like this, so before I save the API response I'm cleaning the data with the following function:

var object_to_return = input_object;

_.forOwn(object_to_return, function(key_value) { 
        if (_.isEmpty(key_value)) {
            object_to_return[key_value] = null;
        }
    });

return object_to_return;

This isn't quite correct and I'm curious if anyone knows why and how I can fix it. I'm especially interested in the why and if I should bother with even returning a copy of the object (is it being passed in by reference, or...?)

Upvotes: 1

Views: 435

Answers (1)

Sean
Sean

Reputation: 63

_.forOwn exposes the key in the callback function; therefore, this worked:

module.exports.convertEmptyObjectsToNull = function(target_object) {
    _.forOwn(target_object, function(property, key) { 
        if (_.isEmpty(property)) {
            target_object[key] = null;
        }
    });
}

Also, as @apsillers mentioned, I wasn't doing much with my assignments, so this method just mutates the input object and doesn't attempt to clone it and return a copy.

Upvotes: 1

Related Questions