0

I can't seem to reach my object variables, I'm probably just doing a dummy mistake somewhere. A console.log of my array of objects (pResult) look like this, first object expanded but they all look alike:

[Object, Object, Object, Object, Object, Object, Object, Object, Object]

0: Object
depTime: "2014-12-04 18:35"
destination: "Norsesund station"
nr: "562"
operator: "Västtrafik"
typText: "Buss"
__proto__: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
length: 9
__proto__: Array[0]

I try to do this...

for (var i = 0; i <= pResult.length; i++) {
    var html =  html + '<tr>';
    var html =  html + '<td>';
    var html =  html + pResult[i].depTime;
    var html =  html + '</td>';
    var html =  html + '</tr>';
}

...but get hit with this error:

Uncaught TypeError: Cannot read property 'depTime' of undefined
2
  • According to your output, pResult.depTime is defined, but pResult[i].depTime is not. Am I missing something? Commented Dec 4, 2014 at 18:05
  • Just an aside: this has nothing to do with JSON; you're dealing with JavaScript objects, not textual notation that describes objects. (If your question dealt with parsing JSON text into objects, then the [json] tag would be appropriate.) Commented Dec 4, 2014 at 18:06

3 Answers 3

3

Change :

i <= pResult.length;

To:

i < pResult.length;

Array is 0 based indexed, so if it has length 3, you only have indexes 0,1,2

Sign up to request clarification or add additional context in comments.

2 Comments

This is what I saw pResult does not exist for pResult[9] ... 9 being the length.
thank you, works. will accept as soon as it lets me.
1

Instead of using a loop, you can simply use reduce:

var html = pResult.reduce(function(previousValue, currentValue) {
    return previousValue + '<tr><td>' + currentValue.depTime + '</td></tr>';
}, '');

Note that this only works on IE 9+ (but it works in all other modern browsers), so if you need to support older versions of IE, you can polyfill the method.

Comments

0

try this:

for (var i = 0; i < pResult.length; i++) {
        var html =   '<tr>';
            html +=  html + '<td>';
                html +=  html + pResult[i].depTime;
            html +=  html + '</td>';
        html +=  html + '</tr>';
}

The problem is you are loopin until arrays length but array start at 0 index so
if you have array
var pResult= [object,object,object];
pResult.length =3
pResult[3] doesnt exist so it is undefined.
NOTE dont recreate the variable when you just want to add text just add it to the existing one For example html+=" the added text"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.