如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
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' }
其他回答
你可以循环遍历对象:
Var检验= { test1:空, test2:“somestring”, test3: 3, } 函数clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { 删除obj [propName]; } } 返回obj } console.log(测试); console.log(清洁(测试));
如果你担心这个属性删除不会运行到对象的proptype链,你还可以:
function clean(obj) {
var propNames = Object.getOwnPropertyNames(obj);
for (var i = 0; i < propNames.length; i++) {
var propName = propNames[i];
if (obj[propName] === null || obj[propName] === undefined) {
delete obj[propName];
}
}
}
关于null和undefined的一些注意事项:
test.test1 === null; // true
test.test1 == null; // true
test.notaprop === null; // false
test.notaprop == null; // true
test.notaprop === undefined; // true
test.notaprop == undefined; // true
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))
来piggypack本的回答如何解决这个问题使用lodash的_。pickBy,你也可以在姐妹库中解决这个问题:Underscore.js的_.pick。
var obj = {name: 'John', age: null};
var compacted = _.pick(obj, function(value) {
return value !== null && value !== undefined;
});
参见:JSFiddle示例
递归地删除null, undefined,空对象和空数组,返回一个副本(ES6版本)
export function skipEmpties(dirty) {
let item;
if (Array.isArray(dirty)) {
item = dirty.map(x => skipEmpties(x)).filter(value => value !== undefined);
return item.length ? item : undefined;
} else if (dirty && typeof dirty === 'object') {
item = {};
Object.keys(dirty).forEach(key => {
const value = skipEmpties(dirty[key]);
if (value !== undefined) {
item[key] = value;
}
});
return Object.keys(item).length ? item : undefined;
} else {
return dirty === null ? undefined : dirty;
}
}
下面是一个综合递归函数(最初基于@chickens的函数),它将:
递归删除你告诉它的默认值=[undefined, null, ", NaN] 正确处理常规对象、数组和Date对象
const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {
if (!defaults.length) return obj
if (defaults.includes(obj)) return
if (Array.isArray(obj))
return obj
.map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)
.filter(v => !defaults.includes(v))
return Object.entries(obj).length
? Object.entries(obj)
.map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))
.reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {})
: obj
}
用法:
// based off the recursive cleanEmpty function by @chickens. // This one can also handle Date objects correctly // and has a defaults list for values you want stripped. const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) { if (!defaults.length) return obj if (defaults.includes(obj)) return if (Array.isArray(obj)) return obj .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v) .filter(v => !defaults.includes(v)) return Object.entries(obj).length ? Object.entries(obj) .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v])) .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) : obj } // testing console.log('testing: undefined \n', cleanEmpty(undefined)) console.log('testing: null \n',cleanEmpty(null)) console.log('testing: NaN \n',cleanEmpty(NaN)) console.log('testing: empty string \n',cleanEmpty('')) console.log('testing: empty array \n',cleanEmpty([])) console.log('testing: date object \n',cleanEmpty(new Date(1589339052 * 1000))) console.log('testing: nested empty arr \n',cleanEmpty({ 1: { 2 :null, 3: [] }})) console.log('testing: comprehensive obj \n', cleanEmpty({ a: 5, b: 0, c: undefined, d: { e: null, f: [{ a: undefined, b: new Date(), c: '' }] }, g: NaN, h: null })) console.log('testing: different defaults \n', cleanEmpty({ a: 5, b: 0, c: undefined, d: { e: null, f: [{ a: undefined, b: '', c: new Date() }] }, g: [0, 1, 2, 3, 4], h: '', }, [undefined, null]))