如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
这是我对鸡肉功能的看法
这将从对象或对象数组中删除空字符串、未定义、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)), {})
}
}
其他回答
Oneliner:
let obj = { a: 0, b: "string", c: undefined, d: null };
Object.keys(obj).map(k => obj[k] == undefined ? delete obj[k] : obj[k] );
控制台.log(卷);
Obj将是{a: 0, b: "string"}
您可能正在寻找delete关键字。
var obj = { };
obj.theProperty = 1;
delete obj.theProperty;
使用ramda#pickBy你将删除所有null, undefined和false值:
const obj = {a:1, b: undefined, c: null, d: 1}
R.pickBy(R.identity, obj)
正如@manroe指出的,要保留假值,请使用isNil():
const obj = {a:1, b: undefined, c: null, d: 1, e: false}
R.pickBy(v => !R.isNil(v), obj)
TypeScript的泛型函数
function cleanProps(object:Record<string, string>):Record<string, string> {
let cleanObj = {};
Object.keys(object).forEach((key) => {
const property = object[key];
cleanObj = property ? { ...cleanObj, [key]: property } : cleanObj;
});
return cleanObj;
}
export default cleanProps;
现在假设你有一个像下面这样的对象
interface Filters{
searchString: string;
location: string;
sector: string
}
const filters:Filters = {
searchString: 'cute cats',
location: '',
sector: 'education',
};
您可以按照如下方式使用该函数
const result = cleanProps(filters as Record<keyof Filters, string>);
console.log(result); // outputs: { searchString: 'cute cats', sector: 'education' }
reduce helper可以做到这一点(不需要类型检查)-
const cleanObj = Object.entries(objToClean).reduce((acc, [key, value]) => {
if (value) {
acc[key] = value;
}
return acc;
}, {});