我有一个具有多个属性的对象,我想使用 lodash 删除空的对象/嵌套对象。做这个的最好方式是什么?
Let template = {
node: "test",
representation: {
range: { }
},
transmit: {
timeMs: 0
}
};
至
template = {
node: "test",
transmit: {
timeMs: 0
}
};
我试过这样的事情,但我迷路了。
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
});
原文由 yesh 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以通过几个步骤实现这一目标:
使用 pickBy() 来选择对象键值,使用 isObject() 谓词。
使用 mapValues() 递归调用
removeEmptyObjects()
,注意它只会用对象调用这个函数。使用带有 isEmpty () 谓词的 omitBy() 移除在
mapValues()
之后找到的所有空对象。使用 assign() 重新分配对象的所有原始值,并使用
omitBy()
和isObject()
谓词。