1

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.

2 Answers 2

1

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]);  
        }
     }
}
Sign up to request clarification or add additional context in comments.

Comments

1

.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

1 Comment

thanks for the info. I checked that property can be accessed using . which i applied here. Thanks for clarification.

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.