This is confusing me to no end. I am trying to update an objects property dynamically based on vars provided by another function however, when I update the property it updates all the same nested properties of the parent object.
export type TopContributing = {
totalInTopFive: number
one: BreakdownForName
two: BreakdownForName
three: BreakdownForName
four: BreakdownForName
five: BreakdownForName
others: BreakdownForName
}
export type BreakdownForName = {
name: string
itemBreakdown: {
cancelled: MetricValue
outstanding: MetricValue
reclassifiedAsIssue: MetricValue
reclassifiedAsValid: MetricValue
}
}
type MetricValue = {
items: object[];
count: number
}
const populateTopOutcomes = (
item: object, //the object to push to topItems
outcome: string, //the itemBreakdown property e.g. outstanding, reclassifiedAsValid, etc.
topItems: TopContributing, // the parent Object that contains Top5Items, others and totalCount.
topFive: string[] // list of names of top items
) => {
const itemIndex = topFive.indexOf(item.name) // find index of which bucket in topItems the item's in
if (itemIndex === 0) {
topItems.one.itemBreakdown[outcome].items.push(item)
topItems.one.itemBreakdown[outcome].count++
}
else if (itemIndex === 1) {
topItems.two.itemBreakdown[outcome].items.push(item)
topItems.two.itemBreakdown[outcome].count ++
}
else if (itemIndex === 2) {
topItems.three.itemBreakdown[outcome].items.push(item)
topItems.three.itemBreakdown[outcome].count ++
}
else if (itemIndex === 3) {
topItems.four.itemBreakdown[outcome].items.push(item)
topItems.four.itemBreakdown[outcome].count ++
}
else if (itemIndex === 4) {
topItems.five.itemBreakdown[outcome].items.push(item)
topItems.five.itemBreakdown[outcome].count ++
}
else if (itemIndex < 0) {
topItems.others.itemBreakdown[outcome].items.push(item)
topItems.others.itemBreakdown[outcome].count ++
}
}
The issue I run into is when I access the MetricValue object in topItems.{property}.itemBreakdown[outcome] using outcome, it updates that property (items or count) in all of the objects in the TopContributing object. For Example if I try to update outcome "outstanding" in topItems.one it will add that same value to topItems.two, three, etc. What's going on? I can't figure out why this happens. Any help would be great!