I am getting a json response and storing it in mongodb, however the fields that I don\'t need are also getting in to the database, is there anyway to strip the uneseccary fi
If you want to do this in a strongly-typed way, you can define a dummy/ideal object which satisfies your interface (const dummy: IMyInterface = {someField: "someVal"};
), and then filter incoming objects' fields against Object.keys(dummy)
. This way your compiler will complain if you update the interface without updating this 'filtering' code.
You can use a function that picks certain properties from a given object:
function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
const copy = {} as Pick<T, K>;
keys.forEach(key => copy[key] = obj[key]);
return copy;
}
Then:
let obj = { "name": "someName", "age": 20 };
let copy = pick(obj, "name") as Test;
console.log(copy); // { name: "someName" }
Suppose you want to remove age
temp = {...temp, age: undefined}
This will remove age
from your object for good.