I have an object with several properties and I would like to remove objects/nested objects that are empty, using lodash. What is the best way to do this?
Let template = {
node: "test",
representation: {
range: { }
},
transmit: {
timeMs: 0
}
};
to
template = {
node: "test",
transmit: {
timeMs: 0
}
};
I tried something like this, but I am lost.
Utils.removeEmptyObjects = function(obj) {
return _.transform(obj, function(o, v, k) {
if (typeof v === 'object') {
o[k] = _.removeEmptyObjects(v);
} else if (!_.isEmpty(v)) {
o[k] = v;
}
});
};
_.mixin({
'removeEmptyObjects': Utils.removeEmptyObjects
});
You can achieve this through several steps:
Use pickBy() to pick object key-values, using the isObject() predicate.
Use mapValues() to recursively call
removeEmptyObjects(), note that it would only invoke this function with objects.Remove all empty objects that are found after the
mapValues()using omitBy() with an isEmpty() predicate.Assign all primitive values from the object all over again using assign() for assignment, and
omitBy()with anisObject()predicate.
function removeEmptyObjects(obj) {
return _(obj)
.pickBy(_.isObject) // pick objects only
.mapValues(removeEmptyObjects) // call only for object values
.omitBy(_.isEmpty) // remove all empty objects
.assign(_.omitBy(obj, _.isObject)) // assign back primitive values
.value();
}
function removeEmptyObjects(obj) {
return _(obj)
.pickBy(_.isObject)
.mapValues(removeEmptyObjects)
.omitBy(_.isEmpty)
.assign(_.omitBy(obj, _.isObject))
.value();
}
_.mixin({
removeEmptyObjects: removeEmptyObjects
});
var template = {
node: "test",
representation: {
range: {}
},
transmit: {
timeMs: 0
}
};
var result = _.removeEmptyObjects(template);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
You could use _.pick to choose only the properties you want, as in
var desiredTemplate = _.pick(template, ['node','transmit']);
Otherwise, as far as I can tell, lodash has nothing built in that can recursively remove empty objects/arrays from an object.
来源:https://stackoverflow.com/questions/38275753/how-to-remove-empty-values-from-object-using-lodash