简体   繁体   English

在JavaScript中删除forEach内部的forEach

[英]Remove a forEach inside of a forEach in JavaScript

In my code, I have used two forEach loops. 在我的代码中,我使用了两个forEach循环。 But in order to optimize my code, I have been told to remove the inner forEach. 但是为了优化代码,我被告知删除内部的forEach。 I have been instructed not to use a forEach loop inside a forEach loop. 我被指示不要在forEach循环内使用forEach循环。 So I don't want to loop over the second array obj3. 所以我不想遍历第二个数组obj3。 I just want to get the values at a certain position. 我只想在某个位置获取值。 Here is my code : - 这是我的代码:-

var obj2 = [{
  "name": "4134",
  "calls": [

  ]
}]

    var obj3 = [{ Channel: 'SIP/4134-0004462a',
        State: 'Up',
        Accountcode: '7013658596'},
      { Channel: 'SIP/4334-sa',
        State: 'Up',
        Accountcode: '07717754702',
      }]


var function = (obj2, obj3) => {
    obj2.forEach((a) =>
      obj3.forEach((b) => {
        if (b.Channel.includes(a.name)) a.calls = (a.calls || []).concat(Object.assign({}, { MobileNo: b.Accountcode, Status : b.State}));

      })
    );
};

function(obj2, obj3);

The above code loops through obj2 and obj3 and if the value of the name key exist in the Channel key's value then it picks the Accountcode and State from obj3 and pushes them in the calls array of the obj2. 上面的代码循环遍历obj2和obj3,如果名称键的值存在于Channel键的值中,则它将从obj3中选择Accountcode和State并将它们推入obj2的calls数组中。 Here is the output array:- 这是输出数组:

    [ {
  "name": "4134",
  "calls": [
    {
      "MobileNo": "7013658596",
      "Status": "Up"
    }
  ]
}]

Any suggestions about how to tackle this? 关于如何解决这个问题的任何建议?

Try This 尝试这个

var channelArr = [];
const Channels = obj3.reduce((acc, curVal) => {
  obj2.forEach((item)=>{
    if(item.name == curVal.Channel.slice(4,8).toString()){
      item.calls.push({'MobileNo':curVal.Accountcode,'Status': curVal.State})
    }
  })
  return obj2;
}, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM