_.forEach循环值更改所有继承的数据

时间:2016-11-18 20:51:29

标签: angular typescript foreach underscore.js lodash

我尝试嵌套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"
  }
 ]
}
]

1 个答案:

答案 0 :(得分:1)

  • 不知道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>