这让我困惑不已。我正在尝试根据另一个函数提供的变量动态更新对象属性,但是,当我更新属性时,它会更新父对象的所有相同嵌套属性。
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 中更新结果“优秀”,它会将相同的值添加到 topItems.two、3 等。这是怎么回事?我不明白为什么会这样。任何帮助都会很棒!