在我们前后端联调的过程中,一系列的参数去后端查询接口,为了提升查询速度,前端需要把字段为空"",null,undefined,参数给去掉,那么我们就可以使用以下方法:
function removeEmptyProperties(obj) {
const newObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {
newObj[key] = obj[key];
}
}
return newObj;
}
const originalObject = {
type: "book",
user: "Alice",
storeName: undefined,
storeId: undefined,
storeData: "",
storeDataId: null,
};
const objectWithoutEmptyProperties = removeEmptyProperties(originalObject);
console.log(objectWithoutEmptyProperties);
// 输出: { type: 'book', user: 'Alice', tenantId: '123' }