In my code, I have used two forEach loops. But in order to optimize my code, I have been told to remove the inner forEach. I have been instructed not to use a forEach loop inside a forEach loop. So I don't want to loop over the second array 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. Here is the output array:-
[ {
"name": "4134",
"calls": [
{
"MobileNo": "7013658596",
"Status": "Up"
}
]
}]
Any suggestions about how to tackle this?
obj2andobj3and also what you'd like the result to look like?