When the length of my 2 json arrays are the same, I don't get an error. But when they aren't I get a TypeError: Connot read property of undefined
.
JSON:
json1:
[
{
"date": "2019-07-05",
"x": 1246567,
"y": 598045
},
{
"date": "2019-07-06",
"x": 1021607,
"y": 452854
},
{
"date": "2019-07-07",
"x": 1031607,
"y": 467854
}
]
json2:
[
{
"date": "2019-07-05",
"v": 3132769,
"pv": 6643094
},
{
"date": "2019-07-06",
"v": 2643611,
"pv": 6059584
}
]
JavaScript
$.getJSON(json1, result => {
result.forEach((elem, i, array) => {
$('#x').text(elem.x);
$('#y').text(elem.y);
});
$.getJSON(json2, result => {
result.forEach((elem, i, array) => {
let yo = 0;
if ((elem.date.indexOf(json[i].date) !== -1)) {
yo = json[i].x/elem.v)
$('#v').text(elem.v);
$('#pv').text(elem.pv);
$('#vpv').text(yo);
}
});
});
Everything is ok when the length of the arrays match each other. But when one is longer than the other, I get
TypeError: Cannot read property x of undefined (at json[i].x).
I am even adding the condition
if ((elem.date.indexOf(json[i].date) !== -1)).
I thought that would fix that. But I am still getting the error. How can I fix this?