如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
如果你正在使用lodash或underscore.js,这里有一个简单的解决方案:
var obj = {name: 'John', age: null};
var compacted = _.pickBy(obj);
这将只适用于lodash 4,预lodash 4或下划线。js,使用_。选择(obj _.identity);
其他回答
我在我的项目中有同样的场景,并使用以下方法实现。
它适用于所有数据类型,上面提到的一些数据类型不适用于日期和空数组。
removeEmptyKeysFromObject.js
removeEmptyKeysFromObject(obj) { Object.keys(obj).forEach(key => { if (Object.prototype.toString.call(obj[key]) === '[object Date]' && (obj[key].toString().length === 0 || obj[key].toString() === 'Invalid Date')) { delete obj[key]; } else if (obj[key] && typeof obj[key] === 'object') { this.removeEmptyKeysFromObject(obj[key]); } else if (obj[key] == null || obj[key] === '') { delete obj[key]; } if (obj[key] && typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0 && Object.prototype.toString.call(obj[key]) !== '[object Date]') { delete obj[key]; } }); return obj; }
将任何对象传递给该函数
ES6 arrow function and ternary operator:
Object.entries(obj).reduce((acc, entry) => {
const [key, value] = entry
if (value !== undefined) acc[key] = value;
return acc;
}, {})
const obj = {test:undefined, test1:1 ,test12:0, test123:false};
const newObj = Object.entries(obj).reduce((acc, entry) => {
const [key, value] = entry
if (value !== undefined) acc[key] = value;
return acc;
}, {})
console.log(newObj)
下面是一个综合递归函数(最初基于@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]))
如果你正在使用lodash或underscore.js,这里有一个简单的解决方案:
var obj = {name: 'John', age: null};
var compacted = _.pickBy(obj);
这将只适用于lodash 4,预lodash 4或下划线。js,使用_。选择(obj _.identity);
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' }