我正在获取一个json响应并将其存储在mongodb中,但是我不需要的字段也正在进入数据库中,是否仍要剥离unseccary字段?
interface Test{ name:string }; const temp :Test = JSON.parse('{ "name":"someName","age":20 }') as Test; console.log(temp);
输出:
{ name: 'someName', age: 20 }
您可以使用从给定对象中选取某些属性的函数:
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; }
然后:
let obj = { "name": "someName", "age": 20 }; let copy = pick(obj, "name") as Test; console.log(copy); // { name: "someName" }