Bekzod
Bekzod

Reputation: 133

Remove fields from typescript interface object

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 }

Upvotes: 9

Views: 19334

Answers (4)

Ramesh-X
Ramesh-X

Reputation: 5085

Let say you have this object.

const x = {a: 1, b: 2, c: 3};

If you want to make a object with only a and b, you can use the following method.

const {c, ...y} = x;
console.log(y);

You will see that y has only a and b now.
Also this will not give an error if the field c was not in x. As an example,

const x: any = {a: 1, b: 2, c: 3};
const {d, ...y} = x;
console.log(y);

This works perfectly fine without any error and if you log the value of d, it will be undefined.

Upvotes: 4

Jordan Morris
Jordan Morris

Reputation: 2301

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.

Upvotes: 0

Nitzan Tomer
Nitzan Tomer

Reputation: 164467

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" }

Upvotes: 15

borislemke
borislemke

Reputation: 9146

Suppose you want to remove age

temp = {...temp, age: undefined}

This will remove age from your object for good.

Upvotes: 3

Related Questions