I have an object listData with the following values:
{
"TestId": 2,
"CurrentTestVersion": 1,
"TestNumber": "2015-29059",
"SharingData": 1.000000,
"ThresholdValue": 0.0,
"ExpireDate": "2022-12-31T00:00:00",
"UpdateDate": "2021-10-01T00:00:00",
"TestCurrency": "INR",
"TestCode": "44300",
"TestUCode": "",
"IndexType": "LME",
"IndexCode": "EUR",
}
I need to create one more object with only selected fields like:
{
"TestId": 2,
"CurrentTestVersion": 1,
"ThresholdValue": 0.0,
"ExpireDate": "2022-12-31T00:00:00",
"TestCurrency": "INR",
"TestCode": "44300",
"TestUCode": "",
}
I have checked with What is the most efficient way to copy some properties from an object in JavaScript?, which works well with JavaScript but not with TypeScript; any better ways to selectively copy properties?
CodePudding user response:
I think you need a mapper something like this:
const objMapper = (obj: { [key: string]: string | number }, keys: string[]) => {
const result: { [key: string]: string | number } = {};
for (const k of keys) {
if (obj[k]) {
result[k] = obj[k];
}
}
return result;
};
and you can call it like this:
const result = objMapper({
"TestId": 2,
"CurrentTestVersion": 1,
"TestNumber": "2015-29059",
"SharingData": 1.000000,
"ThresholdValue": 0.0,
"ExpireDate": "2022-12-31T00:00:00",
"UpdateDate": "2021-10-01T00:00:00",
"TestCurrency": "INR",
"TestCode": "44300",
"TestUCode": "",
"IndexType": "LME",
"IndexCode": "EUR",
}, ["TestId", "CurrentTestVersion", ...]);
and it will return your custom object
CodePudding user response:
You don't need to remove the extra property, since you are working with type script, you must have two interface/class to represent respective the structures. eg:
AllProperty ap; // source
SomeProperty sp; // target
// Sine in your example your object does not have any reference type property ,
// you can simply transfer the values to a new object.
var sp = Object.assign(sp, ap) as SomeProperty;
If you want to remove properties for some other reason (data being sent through API)
you can either use 'delete' keyword, ... spread operator etc
