[英]How to remove empty object from JSON recursively using lodash
var template = {
personal: {},
education: {},
certificate: [{"test": "Test"}, {}, {}],
experience: []
}
removeEmptyObj(template);
function removeEmptyObj(obj)
for (var key in obj) {
console.log("Foor Loop" + key + " " + obj[key]);
if (_.isObject(obj[key]) && !_.isEmpty(obj[key])) {
console.log("Second Loop Object:::" + key + " " + obj[key]);
removeEmptyObj(obj[key]);
}
if (_.isEmpty(obj[key])) {
console.log("Delete Object:::" + key + " " + obj[key]);
obj = _.omitBy(obj, _.isEmpty);
}
}
console.log(obj);
return obj;
}
當前輸出是: {certificate: [{"test": "Test"}, {}, {}]}
所需的輸出: {certificate: [{"test": "Test"}]}
這里有什么問題,感謝您的幫助:)
您可以_.transform()
遞歸地將對象轉換為新對象,並在途中清理空對象和數組。
注意:為了演示,我在結構中添加了更多元素
var template = { personal: {}, education: {}, certificate: [{}, {"test": "Test"}, {}, {}, [{}], [{}, 1, []]], experience: [[1, 2, [], { 3: [] }]] }; function clean(el) { function internalClean(el) { return _.transform(el, function(result, value, key) { var isCollection = _.isObject(value); var cleaned = isCollection ? internalClean(value) : value; if (isCollection && _.isEmpty(cleaned)) { return; } _.isArray(result) ? result.push(cleaned) : (result[key] = cleaned); }); } return _.isObject(el) ? internalClean(el) : el; } console.log(clean(template));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
你可以使用這個函數,區分普通對象和數組:
// Helper function var isEmptyObject = _.overEvery(_.isObject, _.isEmpty); // Actual function function removeEmptyObj(obj) { return _.isArray(obj) ? _.reject(_.map(obj, removeEmptyObj), isEmptyObject) : _.isObject(obj) ? _.omitBy(_.mapValues(obj, removeEmptyObj), isEmptyObject) : obj; } // Example var template = { personal: {}, education: {}, certificate: [{"test": "Test"}, {}, {}], experience: [] } var result = removeEmptyObj(template); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
不需要 Lodash。 一個簡單的過濾器就可以了。
var template = { personal: {}, education: {}, certificate: [{"test": "Test"}, {}, {}], experience: [] } template.certificate = template.certificate.filter(o => Object.keys(o).length) console.log(template.certificate)
您是否嘗試過 _.omit(certificate, [{}])。 我從未嘗試過,但請告訴我
你可以試試這個方法,用你的例子對我有用。 我很確定我們可以用更好的 lodash 方式做,但至少你可以解除封鎖
deepOmit(obj) {
function omitFromObject(obj) {
return _.transform(obj, function(result, value, key) {
if (_.isNull(value) || _.isUndefined(value) || _.isEmpty(value)) {
return;
}
result[key] = _.isObject(value) ? omitFromObject(value) : value;
});
}
return omitFromObject(obj);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.