2
我想嵌套2 _.forEach;_.forEach循环值更改所有继承的数据
_.forEach(this.operationTypes, (value: any, key) => {
value.Terms = [];
this.operationLimits.push(value);
_.forEach(this.operationTerms, (subValue: OperationTerm, subKey) => {
let typeTerms = _.filter(this.operationTypeTerms, { OperationType: { Id: value.Id }, OperationTerm: { Id: subValue.Id } });
subValue.TypeTerms = typeTerms[0];
this.operationLimits[key].Terms.push(subValue);
});
});
但它创建所有TypeTerms
值与最后一个循环的值相同。 这意味着新的值从我的foreach循环subValue
继承,如果subValue
更改,所有从此分配将自动更改。
如何防止?
感谢
编辑:
它应该是这个样子。
[
{
Active: true,
Id: 2,
Name: "Cash Out",
Terms: [
{
Id: 2,
Name: "Daily Limit",
TypeTerms: "Forbidden" -> all of these are same 'forbidden', but it could be 'forbidden' or 'allowed'. At the end of the loop all data changed to forbidden, because the last datas TypeTerms value is 'forbidden'
},
{
Id: 3,
Name: "Weekly Limit",
TypeTerms: "Forbidden"
}
]
},
{
Active: true,
Id: 3,
Name: "Top Up",
Terms: [
{
Id: 2,
Name: "Daily Limit",
TypeTerms: "Forbidden"
},
{
Id: 3,
Name: "Weekly Limit"
TypeTerms: "Forbidden"
}
]
}
]
两个嵌套循环和过滤器看起来像一个候选人重构。你能提供一小部分你的输入数据和你想要的输出吗? – jmargolisvt
更新基础条目 –