I have the following arrays:
//data
[
{
"idAgen":36,
"asesor":"ARCANGEL",
"idRegion":3,
"region":"U",
"idZona":3,
"zona":"ARIO",
"campos":291
},
{
"idAgen":67,
"asesor":"MIGUEL",
"idRegion":3,
"region":"U",
"idZona":3,
"zona":"ARIO",
"campos":888
},
{
"idAgen":90,
"asesor":"JOSE",
"idRegion":3,
"region":"U",
"idZona":3,
"zona":"ARIO",
"campos":291
}
]
//pronostico
[
{
"idAgen": 36,
"pronostico": 410693
},
{
"idAgen": 36,
"pronostico": 8347
},
{
"idAgen": 67,
"pronostico": 9877
},
{
"idAgen": 67,
"pronostico": 9000
},
{
"idAgen": 67,
"pronostico": 5363
},
{
"idAgen": 90,
"pronostico": 896
}
]
And what I'm trying to do is the following (for each data object):
[
{
"idAgen":36,
"asesor":"ARCANGEL",
"idRegion":3,
"region":"U",
"idZona":3,
"zona":"ARIO",
"campos":291,
"pronostico":[
{
"pronostico": 410693
},
{
"pronostico": 8347
}
]
}
]
I've tried this but it doesn't work, it adds the values separately, like so:
//data
[
{
"idAgen":36,
"asesor":"ARCANGEL",
"idRegion":3,
"region":"U",
"idZona":3,
"zona":"ARIO",
"campos":291
},
{
"pronostico": 410693
},
{
"pronostico": 8347
}
]
First I iterate both arrays, I start with forecast since it is bigger than data, then I iterate data, where the idAgen property is the same in both, add the forecast values with push.
for (var i = 0; i < pronostico.length; i++)
{
for (var j = 0; j < data.length; j++) {
if (pronostico[i]['idAgen'] == data[j]['idAgen'])
{
data.push({pronostico :pronostico[i]['pronostico']});
}
}
}
console.log(JSON.stringify(data));