如何将某些属性从一个对象复制到另一个对象



我有一个具有以下值的对象listData

{
"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": 2,
"CurrentTestVersion": 1,
"ThresholdValue": 0.0,
"ExpireDate": "2022-12-31T00:00:00",
"TestCurrency": "INR",
"TestCode": "44300",
"TestUCode": "",
}

我已经检查了在JavaScript中从对象复制某些属性的最有效方法是什么?,它与JavaScript配合良好,但与TypeScript配合不好;有什么更好的方法可以选择性地复制属性?

我想你需要一个类似这样的映射器:

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

你可以这样称呼它:

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", ...]);

它将返回您的自定义对象

您不需要删除额外的属性,因为您使用的是类型脚本,您必须有两个接口/类来表示各自的结构。例如:

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;

如果您出于其他原因想要删除属性(通过API发送数据(

you can either use 'delete' keyword, ... spread operator etc

最新更新