Mahadeva
Mahadeva

Reputation: 1637

Accessing the Property of Javascript object failing

I have a JS function that needs to have object as its parameter. I want to get the property and values of the object. Following is the list of JS object in my program:

var a =[{'Jan':1555},{'Feb':456},{'Mar':987},{'Apr':768}];

As expected to get the property and values one can use for loop here like below:

for(var i=0;i<a.length;i++){
for(var j in a[i]){
    console.log(j);        // Here it returns the property correctly
    console.log(a[i].j);  //Returns Error here ie returns undefined
     }
}

Now above line console.log(a[i].j) returns undefined values while if manually checking the list like a[0].Jan I get 1555 , a[1].Feb returns 456 and so on. Why is this so? Please correct the code if I am wrong as i am new in JS.

Upvotes: 1

Views: 58

Answers (2)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

.j property doesn't exist, You should do it like this:

for(var i=0;i<a.length;i++){
    for(var j in a[i]){
        console.log(j);        // Here it returns the property correctly
        console.log(a[i][j]);  //Now works
     }
}

However, I'd write it as the following to be more understandable:

for(var i=0; i < a.length; i++){
    var item = a[i];
    for(var month in item){
        console.log("month: ", month);        
        console.log("value: ", item[month]);
     }
}

Cheers

Upvotes: 1

scrblnrd3
scrblnrd3

Reputation: 7416

You have to access it with console.log(a[i][j]);

Accessing it with a[i].j is like accessing it with a[i]["j"], which isn't what you want. Also, whenever you use for ... in, you should always check it with obj.hasOwnProperty

Use this code instead

for(var i=0;i<a.length;i++){
    for(var j in a[i]){
        if(a[i].hasOwnProperty(j){
            console.log(j);        // Here it returns the property correctly
            console.log(a[i][j]);  
        }
     }
}

Upvotes: 1

Related Questions