这使我困惑不已。我正在尝试根据另一个函数提供的变量动态更新对象属性,但是,当我更新该属性时,它将更新父对象的所有相同嵌套属性。
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 ++
}
}
我遇到的问题是,当我使用结果访问topItems。{property} .itemBreakdown [outcome]中的MetricValue对象时,它将更新TopContributing对象中所有对象的属性(项目或计数)。例如,如果我尝试更新topItems.one中的结果“ outstanding”,它将为topItems.two,two,3等添加相同的值。这是怎么回事?我不知道为什么会这样。任何帮助都会很棒!