I’m working on a script that will loop through something similar to the following
$( document ).ready(function() {
let myObj = {};
initLoop();
function initLoop() { //this loads the initial frames into the object
$('.looper').each(function(i, e){
var attr1 = $(this).attr('attr1');
var attr2 = $(this).attr('attr2');
var attr3 = $(this).attr('attr3');
var contents = $(this).html();
myObj[attr1][attr2][attr3] = contents;
});
}
});
I’m looping through a set of divs structured like this…
<div class="looper" attr1="1" attr2="1" attr3="1">content</div>
<div class="looper" attr1="1" attr2="1" attr3="2">content</div>
<div class="looper" attr1="1" attr2="1" attr3="3">content</div>
<div class="looper" attr1="1" attr2="2" attr3="1">content</div>
<div class="looper" attr1="1" attr2="2" attr3="2">content</div>
<div class="looper" attr1="1" attr2="2" attr3="3">content</div>
<div class="looper" attr1="1" attr2="3" attr3="1">content</div>
<div class="looper" attr1="1" attr2="3" attr3="2">content</div>
<div class="looper" attr1="1" attr2="3" attr3="3">content</div>
I’m getting the error
jQuery.Deferred exception: Cannot read properties of undefined (reading ‘1’) TypeError: Cannot read properties of undefined (reading ‘1’)
I’m a bit lost on why this isn’t working.
Can anyone suggest any changes?
2
Answers
I think
myObj
doesn’t have'1'
field.So,
myObj[attr1]
isundefined
.As a result,
myObj[attr1][attr2]
generate error.I add some example code below.
Hope to help you even a little.
It seems like the issue is related to the fact that you are trying to access properties of an object that may not exist yet. Specifically, when you try to access
myObj[attr1][attr2][attr3]
, it’s possible thatmyObj[attr1]
ormyObj[attr1][attr2]
is undefined.To fix this, you need to make sure that each level of the object hierarchy exists before trying to access its properties. Here’s an updated version of your code:
This modification ensures that
myObj[attr1]
andmyObj[attr1][attr2]
are initialized as empty objects if they don’t exist yet. That way, you won’t encounter the "Cannot read properties of undefined" error.Make sure to adjust this code according to your exact requirements and the structure of your data.