I'm working on a generic Angular component that determines the correct type of class to instantiate, sets the properties for the class, & sends the instance to the correct service. The problem is that I'm having a hard time setting the properties, because I can't seem to set any of the properties based on the object keys that I've been able to pull from the instance. Does anyone know how I can iterate through such an object & set the properties? Code is below:
submitNewData(): void {
let data = ClassTool.getInstance(this.dataType.toString());
let keys: string[] = Object.keys(data);
console.log('Data -> ', data);
console.log('Data Keys -> ', keys);
console.log('Data Keys 1 -> ', eval(data.constructor.name + "." + keys[1])); <--------this is a problem
for (let i in this.inputNames) {
if (data.hasOwnProperty(i)) {
data[i] = this.inputNames[i]; <--------this is a problem
}
}
console.log('Data -> ', data);
}
Solved:
submitNewData(): void {
let data = ClassTool.getInstance(this.dataType.toString());
let keys: string[] = Object.keys(data);
for (let index in this.inputNames) {
Object.defineProperty(data, this.inputNames[index], { value: (document.getElementById(this.inputNames[index]) as HTMLInputElement).value });
}
console.log('Data -> ', data);
}