如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
这是另一种选择
打字稿:
function objectDefined <T>(obj: T): T {
const acc: Partial<T> = {};
for (const key in obj) {
if (obj[key] !== undefined) acc[key] = obj[key];
}
return acc as T;
}
Javascript:
function objectDefined(obj) {
const acc = {};
for (const key in obj) {
if (obj[key] !== undefined) acc[key] = obj[key];
}
return acc;
}
其他回答
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)
清洁物体到位
// 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)
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' }
您可能正在寻找delete关键字。
var obj = { };
obj.theProperty = 1;
delete obj.theProperty;
如果你正在使用lodash或underscore.js,这里有一个简单的解决方案:
var obj = {name: 'John', age: null};
var compacted = _.pickBy(obj);
这将只适用于lodash 4,预lodash 4或下划线。js,使用_。选择(obj _.identity);