Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  48] [ 7]  / answers: 1 / hits: 16876  / 7 Years ago, fri, may 26, 2017, 12:00:00

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 }

More From » json

 Answers
12

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 }

[#57648] Wednesday, May 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cristinadomoniquel

Total Points: 320
Total Questions: 94
Total Answers: 94

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
cristinadomoniquel questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Mon, Aug 17, 20, 00:00, 4 Years ago
;