Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  94] [ 7]  / answers: 1 / hits: 29148  / 8 Years ago, fri, july 8, 2016, 12:00:00

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

More From » object

 Answers
200

You can achieve this through several steps:




  1. Use pickBy() to pick object key-values, using the isObject() predicate.


  2. Use mapValues() to recursively call removeEmptyObjects(), note that it would only invoke this function with objects.


  3. Remove all empty objects that are found after the mapValues() using omitBy() with an isEmpty() predicate.


  4. Assign all primitive values from the object all over again using assign() for assignment, and omitBy() with an isObject() 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>




[#61452] Thursday, July 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
;