TypeError: Cannot read property 'MyProperty' of undefined

Viewed 104

I have an array of object pairs like so:

0: pairs {_stim1: {img: "images/F111C.png", gender: 0, rating: "3"}, _stim2: {img: "images/F042C.png", gender: 0, rating: "3"}}
1: pairs {_stim1: {…}, _stim2: {…}}
2: pairs {_stim1: {…}, _stim2: {…}}
3: pairs {_stim1: {…}, _stim2: {…}}
4: pairs {_stim1: {…}, _stim2: {…}}
5: pairs {_stim1: {…}, _stim2: {…}}
6: pairs {_stim1: {…}, _stim2: {…}}
7: pairs {_stim1: {…}, _stim2: {…}}

I am trying to reduce the array to 6 pairs and as close to 3 pairs of each gender property (1 or 0) as possible. To do this I have this clumsy solution where I iterate over the list and append 3 pairs objects with gender: 0 to a list and then 3 with gender: 1, like this:

pair_count = 0;
if ((stim_pairs.length > 6)) {
    for (var i, _pj_c = 0, _pj_a = stim_pairs, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c += 1) {
        i = _pj_a[_pj_c];
        if ((pair_count < 3)) {
            if ((i.stim1.gender === 0)) {
                initial_stim_pairs.push(i);
                final_stim_pairs.push(i);
                pair_count += 1;
            }
        }
    }
    for (var i, _pj_c = 0, _pj_a = stim_pairs, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c += 1) {
        i = _pj_a[_pj_c];
        if ((pair_count < 6)) {
            if ((i.stim1.gender === 1)) {
                initial_stim_pairs.push(i);
                final_stim_pairs.push(i);
                pair_count += 1;
            }
        }
    }
}

However, I 'i.stim1' and 'i.stim2' returns 'undefined'... and I get this error:

'Cannot read property 'gender' of undefined'

What am I doing wrong?

2 Answers

you can validate if i.stim1.gender property exists

if(typeof i.stim1.gender !== 'undefined'){ //your code here}

I have resolved your errors from your code so it is working, but you won't be getting the correct answer from it. The initial issue was it should be i._stim1.gender and not i.stim1.gender. After that some declarations are missing, make sure you use a debugger and run this code on your console to understand the issue.

var pair_count = 0,
initial_stim_pairs = [],
final_stim_pairs = [];
if ((stim_pairs.length > 6)) {
    for (var i, _pj_c = 0, _pj_a = stim_pairs, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c ++) {
        i = _pj_a[_pj_c];
debugger;
        if ((pair_count < 3)) {
            if ((i._stim1.gender === 0)) {
                initial_stim_pairs.push(i);
                final_stim_pairs.push(i);
                pair_count += 1;
            }
        }
    }
    for (var i, _pj_c = 0, _pj_a = stim_pairs, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c += 1) {
        i = _pj_a[_pj_c];
        if ((pair_count < 6)) {
            if ((i._stim1.gender === 1)) {
                initial_stim_pairs.push(i);
                final_stim_pairs.push(i);
                pair_count += 1;
            }
        }
    }
}
Related