我有一个使用Angular 7的嵌套对象,想删除空白部分:
componentDidMount() {
window.addEventListener('resize', this.onWindowResize);
}
onWindowResize = e => {
// I want to open a modal without changing the orientation here
e.preventDefault(); // Not working
e.stopPropagation(); // Not working
alert('Alert! Your screen size altered.');
// The problem here is the screen size changed and then it is showing the alert. I don't want to change it.
};
我在这里找到的其他Javascript解决方案在这里不适用于我,因为我无法以某种方式在removeEmpty()中调用removeEmpty():
carrier:{
name:'',
street:null,
zip:'zip',
city:'city',
country:'XY',
contactPerson:{
name:null,
phoneNo:null,
emailAddr:null
}
},
timeSlotOrders:[
{
loadType:'blabla',
moveIn:{
date:moment(this.timeslotForm.controls.moveInDate.value).format('YYYY-MM-DD'),
time:this.timeslotForm.controls.moveInTime.value,
serviceType:this.timeslotForm.controls.moveInLoadingService.value,
addInfo:this.timeslotForm.controls.moveInRemark.value,
service:this.timeslotForm.controls.moveInService.value,
}
nr:0
},
...
有没有办法解决这个问题?
答案 0 :(得分:0)
这是您的carrier
变量的有效示例。您的代码似乎并未删除空对象。
var carrier = {
name: '',
street: null,
zip: 'zip',
city: 'city',
country: 'XY',
contactPerson: {
name: null,
phoneNo: null,
emailAddr: null,
}
};
const removeEmpty = (obj) => {
Object.keys(obj).forEach(key => {
if (obj[key] == null) {
delete obj[key];
} else if (typeof obj[key] === 'object') {
removeEmpty(obj[key]);
// Check if object is empty
if (Object.entries(obj[key]).length === 0 && obj[key].constructor === Object) {
delete obj[key];
}
}
});
return obj;
}
removeEmpty(carrier);
console.log(carrier);