我有三个对象(类),它们如下所示:
class A {
public value1: string;
public value2: string;
public value3: string;
public value4: string;
public value5: string;
}
class B {
public value1: string;
public value2: string;
}
class C {
public value3: string;
public value4: string;
public value5: string;
}
现在我有一个 JSON,它是这样的:
{
"value1": "ONE",
"value2": "TWO",
"value3": "THREE",
"value4": "FOUR",
"value5": "FIVE"
}
我想知道是否有任何干净的方法来转换类
A
上课B
和类(class)C
?我试过这个方法,但是在
map
之后, 类(class) B
拥有来自 A
的所有 5 处房产而不是 B
上定义的 2 个属性.class B {
public value1: string;
public value2: string;
constructor(item: A) {
Object.assign(this, item);
}
}
let arr1: A[{"value1":"ONE","value2":"TWO","value3":"THREE","value4":"FOUR","value5":"FIVE"}];
let arr2 = arr1.map(item => new B(item));
Result: B -> {"value1":"ONE","value2":"TWO","value3":"THREE","value4":"FOUR","value5":"FIVE"}]
instead of
B -> {"value1":"ONE","value2":"TWO"}]
最佳答案
您要求 typescript 修改值
Typescript 不会运行您的代码,只会编译和检查类型安全
您可以做的是:为 B 类定义 null Prop ,并检查键
class A {
public value1: string
public value2: string
public value3: string
public value4: string
public value5: string
}
class B {
public value1: string = undefined // <-- define
public value2: string = undefined // <-- define
constructor (item: A) {
const keys = Object.keys(item) // get items keys
const thisKeys = Object.keys(this) // get this class keys
const limitedItem = keys.reduce((newObj, key) => { // combine same keys
if (thisKeys.includes(key)) {
newObj[key] = item[key]
}
return newObj
}, {})
Object.assign(this, limitedItem) // asign to this class
}
}
const arr1 = [{ value1: '1', value2: '2', value3: '3', value4: '4', value5: '5' }]
let arr2 = arr1.map(item => new B(item))
console.log('arr2', arr2)
// arr2 [ B { value1: '1', value2: '2' } ]
关于 typescript :如何将对象强制转换或分配给属性较少的类型? (从大到小),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57555768/