gpt4 book ai didi

angular - _.forEach 循环值改变所有继承的数据

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:34 24 4
gpt4 key购买 nike

我正在尝试嵌套 2 _.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"
}
]
}
]

最佳答案

  • 不知道 operationTerms、operationTypes & 的输入参数operationTypeTerms,很难产生所需的输出。然而基于问题逻辑和提供的输出我假设输入带来您想要的结果。
  • 请注意,我在这里使用了简单的下划线,但没有使用斜线尽管如此,这不应该影响逻辑

operationTypes = [{
"Active": true,
"Id": 2,
"Name": "Cash Out"
}, {
"Active": true,
"Id": 3,
"Name": "Top Up"
}]

operationTerms = [{
Id: 2,
Name: "Daily Limit"
}, {
Id: 3,
Name: "Weekly Limit"
}]

operationTypeTerms = [{
"operationTypeId": 2,
"operationTermId": 2,
TypeTerms: ["Forbidden"]
}, {
"operationTypeId": 3,
"operationTermId": 3,
TypeTerms: ["Allowed", "Forbidden"]
}, {
"operationTypeId": 3,
"operationTermId": 2,
TypeTerms: ["Forbidden"]
}, {
"operationTypeId": 2,
"operationTermId": 3,
TypeTerms: ["Allowed", "Forbidden"]
}]


var result = [];
_.each(operationTypes, function(type) {
var typeObj = _.extend(type, {});
var terms = [];
_.each(operationTerms, function(term) {
var val = _.extend(term, {});
var typeTermObj = _.filter(operationTypeTerms, {
operationTypeId: type.Id,
operationTermId: term.Id
});
val.TypeTerms = typeTermObj[0].TypeTerms[0];
terms.push(val);
});
typeObj.Terms = terms;
result.push(typeObj)
});

$("#result").html(JSON.stringify(result))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id="result"></div>

关于angular - _.forEach 循环值改变所有继承的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com