英文:
How to copy values dynamically from one object to 'this' without modifying the destination in Typescript?
问题
以下是您要翻译的内容:
"After searching everywhere, I didn't find a working answer.
How to map values dynamically from one object to 'this' without modifying the target in Typescript?
const bigTodo = {
name: "aaaaaaa",
unwantedProperty: "Nooooooo"
}
export class SmallTodo {
name: string;
constructor(bigTodo: any){
_.assign(this,bigTodo) // NOT working
_.assignIn(this,bigTodo) // NOT working
_.merge(this,bigTodo) // NOT working
_.extend(this,bigTodo) // NOT working
Object.assign(this, fields); // NOT working
for (const prop in bigTodo.keys()) {
if (this.hasOwnProperty(prop)) {
this[prop] = bigTodo[prop]; // NOT working not compatible with type 'any'
}
}
}
}
Expected result:
SmallTodo = {
name: "aaaaaaa"
}
UNWANTED result:
SmallTodo = {
name: "aaaaaaa",
unwantedProperty: "Nooooooo"
}
"
英文:
After searching everywhere, I didn't find a working answer.
How to map values dynamically from one object to 'this' without modifying the target in Typescript?
const bigTodo = {
name: "aaaaaaa",
unwantedProperty: "Nooooooo"
}
.....
export class SmallTodo {
name: string;
constructor(bigTodo: any){
_.assign(this,bigTodo) // NOT working
_.assignIn(this,bigTodo) // NOT working
_.merge(this,bigTodo) // NOT working
_.extend(this,bigTodo) // NOT working
Object.assign(this, fields); // NOT working
for (const prop in bigTodo.keys()) {
if (this.hasOwnProperty(prop)) {
this[prop] = bigTodo[prop]; // NOT working not compatible with type 'any'
}
}
}
}
Expected result:
SmallTodo = {
name: "aaaaaaa"
}
UNWANTED result:
SmallTodo = {
name: "aaaaaaa",
unwantedProperty: "Nooooooo"
}
答案1
得分: 1
以下是翻译好的部分:
当您使用某个值初始化属性时,可以在此属性上调用 getOwnProperty。类似于以下方式:
const bigTodo = {
name: "aaaaaaa",
unwantedProperty: "Nooooooo"
}
class SmallTodo {
name: string = "";
constructor(bigTodo: any) {
for (const prop in bigTodo) {
if (this.hasOwnProperty(prop)) {
this[prop as keyof typeof this] = bigTodo[prop];
}
}
}
}
console.log(new SmallTodo(bigTodo));
console.log(bigTodo);
如果您需要进一步的翻译或有其他问题,请随时提出。
英文:
When you initialise property with some value you can call getOwnProperty on this. Something like below
const bigTodo = {
name: "aaaaaaa",
unwantedProperty: "Nooooooo"
}
class SmallTodo {
name: string = "";
constructor(bigTodo: any) {
for (const prop in bigTodo) {
if (this.hasOwnProperty(prop)) {
this[prop as keyof typeof this] = bigTodo[prop];
}
}
}
}
console.log(new SmallTodo(bigTodo));
console.log(bigTodo);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论