Here is my code :
var obj2 = [{
"name": "4134",
"calls": [
]
}]
var obj3 = [{ Channel: 'SIP/4134-0004462a',
Accountcode: '7013658596'},
{ Channel: 'DAHDI-il-4134-sa',
Accountcode: '07717754702',
}]
var func = (obj2, obj3) => {
obj2.forEach((a) =>
obj3.forEach((b) => {
if (b.Channel.includes(a.name)) a.calls = (a.calls || []).concat(Object.assign({}, { MobileNo: b.Accountcode}));
})
);
};
func(obj2, obj3);
console.log(JSON.stringify(obj2));
Link to my JS-Fiddle Here is my current output:
[
{
"name": "4134",
"calls": [
{
"MobileNo": "7013658596"
},
{
"MobileNo": "07717754702"
}
]
}
]
In the above code I have two objects. In obj2
the value of the name key is 4134. In my code I'm checking if this 4134
exists in the value of the Channel key in obj3
by using if (b.Channel.includes(a.name))
. I have used the includes function here. So if 4134 exists in the value of Channel in obj3 then the Accountcode
is pushed into the calls array of obj2
when there's a match. As you can see one of Channel is SIP/4134-0004462a
and the other one is DAHDI-il-4134-sa
. Both of them contain 4134 but I only want to compare the values where the Channel contains the text SIP in it. As you can see in the above output that the Accountcode from both the objects in obj3
are pushed to calls array in obj2
as both the Channels contain 4134. This is not what I want.
Here is the desired output that I want :
[
{
"name": "4134",
"calls": [
{
"MobileNo": "7013658596"
}
]
}
]
In the above-desired output, 4134 is matched only with the Channel containing the text SIP in it. How do I do it using the includes function?