0

I have several json objects returned from a ajax call as:

...
main: [{
 0: { // i'm showing only one... have severals
    IMGNAM0: "856f070054d378fa5681332095257c3c94d5f858.jpg"
    IMGNAM1: "68dfda9de984e914b7027c4a3cda51fb375dd828.jpg"
    IMGNAM2: "da0a1a3f68af208baca5eae23900548b40adfbef.jpg"
    IMGNAM3: "c8b540f8bdfe054e3c888e800b380dd60a4ac371.jpg"
    IMGNAM4: "565eb06485c51123786a88b8d5537c6b45add950.jpg"
    IMGPAT0: "./static/uploaded_images/1/"
    IMGPAT1: "./static/uploaded_images/1/"
    IMGPAT2: "./static/uploaded_images/1/"
    IMGPAT3: "./static/uploaded_images/1/"
    IMGPAT4: "./static/uploaded_images/1/"
 }
}]
...

so, i need to get this obj names dynamically, i make a fast preview with something that i'm trying to do:

var mainlen = data.main.length-1; // get number of obj
for(var i = 0; i <= mainlen; i++){
   for(var j = 0; j <= 4; j++){ // examples to get all 4 obj names
        if(data.main[i].IMGNAM+j != null){
             // trying to get IMGNAM0 concatenate with j
             console.log(data.main[i].IMGNAM+j); 
             console.log(data.main[i].IMGPAT+j);
        }
   }
}

console shows me as not a number (NaN), What is the best way to make this work ?

3
  • for (var key in data.morrows[i]) { /* do something */ }. Commented Mar 8, 2013 at 12:19
  • edit my question, with data.main[i] Commented Mar 8, 2013 at 12:21
  • Ah, didn't even notice the different name. Doesn't matter though, you use a for...in loop to iterate over the property names of an object. Commented Mar 8, 2013 at 12:25

4 Answers 4

1

Instead of using a point to acces to the data, with .IMGNAM+j, use [IMGNAM+j].

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

Comments

0

Use the code as below:

var mainlen = data.main.length-1; // get number of obj
for(var i = 0; i <= mainlen; i++){
   for(var j = 0; j <= 4; j++){ // examples to get all 4 obj names
        if(data.morrows[i].['IMGNAM'+j] != null){
             // trying to get IMGNAM0 concatenate with j
             console.log(data.main[i].['IMGNAM'+j]); 
             console.log(data.main[i].['IMGPAT'+j]);
        }
   }
}

this should solve your problem

2 Comments

data.main[i].['IMGNAM'+j] should be data.main[i]['IMGNAM'+j].
change the if to data.main .
0

You need something like:

 data.morrows[i]["IMGNAM" + j];

Comments

0

Use square brackets to wrap your concatenated string:

if(data.main[i]['IMAGNAM'+j] != null){

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.