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 fields?
interface Test{
name:string
};
const temp :Test = JSON.parse('{ "name":"someName","age":20 }') as Test;
console.log(temp);
output :
{ name: 'someName', age: 20 }
To remove a property from an object in TypeScript, mark the property as optional on the type and use the delete operator. You can only remove properties that have been marked optional from an object.
The TypeScript Omit utility type It will remove the fields you defined. We want to remove the id field from our user object when we want to create a user. type UserPost = Omit<User, 'id'>; const updateUser: UserPost = { firstname: 'Chris', lastname: 'Bongers', age: 32, };
A TypeScript Interface can include method declarations using arrow functions or normal functions, it can also include properties and return types. The methods can have parameters or remain parameterless.
To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With