I have this object model:
export class FrcCapacity {
constructor(
public id?: number,
public frcId?: number,
public capGroupId?: number,
public capGroup?: CapGroup,
public salesProductId?: number,
public p1?: number,
public p2?: number,
public p3?: number,
public p4?: number,
public p5?: number,
public p6?: number,
public p7?: number,
public p8?: number,
public p9?: number,
public p10?: number,
public p11?: number,
public p12?: number,
public total?: number
) {}
}
And I have an array of this, f. e. frcCapacity, filled with objects of the above object model.
I want to write a function, where I want to set the px value of the processed object. For this, I have all needed data and the function body looks like this:
periodValueChange(val: string, rowIndex: number, field: string) {
for (let [key, value] of Object.entries(this.frcCapacity[rowIndex])) {
if (key === field) this.frcCapacity[rowIndex]???
}
}
I'm trying this with Object.entries, but what should I write in place of the ???. How can I access the px field based on the field string parameter?
After some thinking and searching, this solution works:
periodValueChange(val: string, rowIndex: number, field: string) {
let frcCap = this.frcCapacity[rowIndex];
let map = new Map(Object.entries(frcCap));
for (let [key, value] of map) {
if (key === field) {
map.set(field, +val);
}
}
let obj = Array.from(map).reduce(
(obj, [key, value]) => Object.assign(obj, { [key]: value }),
{}
);
this.frcCapacity[rowIndex] = obj;
}
Basically, I needed something like this:
periodValueChange(val: string, rowIndex: number, field: string) {
this.frcCapacity[rowIndex].field = +val;
}
Where the field parameter can be p1, p2, etc.
valasstring, but none ofFrcCapacity's properties have the typestring. Most of them arenumber, and one of them isCapGroup. So why does this take string?FrcCapacity.prototype. The reason it works is the loose typing aroundObject.entriesand the untyped map. You might as well just do(this.frcCapacity[rowIndex] as any)[field] = +val;if you're not worried about type safety.