I want to delete the key from an object of the object if their value is null and type of key is optional.
for example i have interface of the object like this:
Interface IObject {
amount: number;
plan: IPlan;
achieve: IAchieve;
status?: string;
rank?: number;
}
Interface IPlan {
year: string | null;
name: string;
date?: Date;
grade?: number;
}
Interface IAchieve {
pic: string;
name?: string;
date?: Date;
grade?: number;
}
and have value:
let data: IObject = {
amount: 2300;
plan: {
year: null;
name: 'renov';
date: null;
grade: 3;
};
achieve: {
pic: 'John';
name: null;
date: null;
grade: 3;
};
status: 'good';
rank: null;
};
what i did:
Object.keys(data).forEach(obj => {
if (typeof data[obj as keyof typeof IObject] === 'object') {
Object.keys(data[obj as keyof typeof any]).forEach(obj2 => {
if (data[obj as keyof typeof any][obj2] == undefined) {
delete data[obj as keyof typeof any][obj2];
}
});
}
else if (data[obj as keyof typeof any] == undefined) delete data[obj as keyof typeof any];
});
but i get:
"TypeError: Cannot convert undefined or null to object"
I'm expecting result:
data = {
amount: 2300;
plan: {
year: null;
name: 'renov';
grade: 3;
};
achieve: {
pic: 'John';
grade: 3;
};
status: 'good';
};
There are a few problems with this question.
interface not Interface., separator between fields instead of ;.date?: Date should accept Date and undefined. If you want to include null, then you should write it as date?: Date | null.null and undefined.typeof can only be used to retrieve the type of a variable or property. typeof IObject would try to get the type of an interface, which will not work.
obj as keyof typeof any.I want to delete the key from an object of the object if their value is null and type of key is optional.
If I understand this line correctly then you're trying to use the interface definition to do something at runtime.
This will not work, after the typescript has been compiled into javascript, the interfaces will no longer be present in your code.
See The Basics: Erased Types.
You'll need to tackle this problem from a different angle.
Perhaps you could just remove all fields with a value of null from your object no matter what?
If your typings are correct, then this should only touch the fields that are actually nullable.