如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
清洁物体到位
// General cleanObj function
const cleanObj = (valsToRemoveArr, obj) => {
Object.keys(obj).forEach( (key) =>
if (valsToRemoveArr.includes(obj[key])){
delete obj[key]
}
})
}
cleanObj([undefined, null], obj)
纯函数
const getObjWithoutVals = (dontReturnValsArr, obj) => {
const cleanObj = {}
Object.entries(obj).forEach( ([key, val]) => {
if(!dontReturnValsArr.includes(val)){
cleanObj[key]= val
}
})
return cleanObj
}
//To get a new object without `null` or `undefined` run:
const nonEmptyObj = getObjWithoutVals([undefined, null], obj)
其他回答
var testObject = { test1:“零”, test2:空, test3:“somestring”, test4: 3, test5:“定义”, test6:未定义的, } 函数removeObjectItem (obj) { For (var key in obj) { 如果(String (obj(例子))= = =“零”| |字符串(obj(例子))= = =“定义”){ 删除obj(例子); } } 返回obj } console.log (removeObjectItem (testObject))
如果有人需要使用lodash从对象中删除未定义的值,然后这里是我使用的代码。修改它以删除所有空值(null/undefined)非常简单。
function omitUndefinedDeep(obj) {
return _.reduce(obj, function(result, value, key) {
if (_.isObject(value)) {
result[key] = omitUndefinedDeep(value);
}
else if (!_.isUndefined(value)) {
result[key] = value;
}
return result;
}, {});
}
这是我对鸡肉功能的看法
这将从对象或对象数组中删除空字符串、未定义、null,并且不影响Date对象
const removeEmpty = obj => {
if (Array.isArray(obj)) {
return obj.map(v => (v && !(v instanceof Date) && typeof v === 'object' ? removeEmpty(v) : v)).filter(v => v)
} else {
return Object.entries(obj)
.map(([k, v]) => [k, v && !(v instanceof Date) && typeof v === 'object' ? removeEmpty(v) : v])
.reduce((a, [k, v]) => (typeof v !== 'boolean' && !v ? a : ((a[k] = v), a)), {})
}
}
如果你使用eslint并且想要避免绊倒no-param-reassign规则,你可以使用Object。对于一个相当优雅的ES6解决方案,assign与.reduce和计算属性名结合使用:
const queryParams = { a: 'a', b: 'b', c: 'c', d: undefined, e: null, f: '', g: 0 };
const cleanParams = Object.keys(queryParams)
.filter(key => queryParams[key] != null)
.reduce((acc, key) => Object.assign(acc, { [key]: queryParams[key] }), {});
// { a: 'a', b: 'b', c: 'c', f: '', g: 0 }
我们可以使用JSON。stringify和JSON。解析以从对象中删除空白属性。
jsObject = JSON.parse(JSON.stringify(jsObject), (key, value) => {
if (value == null || value == '' || value == [] || value == {})
return undefined;
return value;
});