Here is the object model I am working with:
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
) {}
}
I have an array called frcCapacity
, which is filled with objects based on the above model.
My goal is to write a function that will update the value of a specific field (px
) in the processed object. Here's what the function body looks like:
periodValueChange(val: string, rowIndex: number, field: string) {
for (let [key, value] of Object.entries(this.frcCapacity[rowIndex])) {
if (key === field) this.frcCapacity[rowIndex]???
}
}
I attempted to use Object.entries
but I'm unsure how to access the px
field based on the field
parameter. Can you provide guidance on this?
After some research and experimentation, I found a solution that 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;
}
Essentially, I needed a solution like this:
periodValueChange(val: string, rowIndex: number, field: string) {
this.frcCapacity[rowIndex].field = +val;
}
Where the field
parameter can be p1
, p2
, and so on.