Remove fields from typescript interface object

后端 未结 3 564
余生分开走
余生分开走 2020-12-11 05:11

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

相关标签:
3条回答
  • 2020-12-11 05:38

    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.

    0 讨论(0)
  • 2020-12-11 05:56

    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" }
    
    0 讨论(0)
  • 2020-12-11 06:00

    Suppose you want to remove age

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

    This will remove age from your object for good.

    0 讨论(0)
提交回复
热议问题