0

OKAYSO, I'm working with some JSON data and formatting it into the DOM, and I'm trying to avoid stuff that looks like this...

var image1 = content.list.story[1].image[0].crop[1].src;
var image2 = content.list.story[1].image[0].crop[1].src;
var image3 = content.list.story[2].image[0].crop[1].src;
var image4 = content.list.story[3].image[0].crop[1].src;

To avoid that, I'm using the following for loop

var count ;
for(count = 0; count < 1; count++){
   console.log("content.list.story["+[count]+"].image[0].crop[1].src");
};

That code prints

content.list.story[0].image[0].crop[1].src

Exactly as it should. However, when I format it to print the actual resource, as such...

var count ;
for(count = 0; count < 1; count++){
   console.log(content.list.story['+[count]+'].image[0].crop[1].src);
};

...it returns undefined.

Any idea what I'm screwing up here?

1
  • content.list.story[count].image[0].crop[1].src Commented Mar 1, 2017 at 19:05

3 Answers 3

3

The correct code is:

var count ;
for(count = 0; count < 1; count++){
    console.log(content.list.story[count].image[0].crop[1].src);
};

You should use variable with index, in your example, you had put index "[count]" and correct index is "0".

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

Comments

1

try the code below:

  var count ;
 for(count = 0; count < 1; count++){
   console.log(content.list.story[count].image[0].crop[1].src);
 };

Comments

1

I think you are using index from 1 to 4 and you are using 0 in loop. So the array[0] is undefined.

Also even if JSON index begins at 0, the code should be like below, note using "story[count]" not story['+[count]+']

var count ;
for(count = 0; count < 1; count++){
   console.log(content.list.story[count].image[0].crop[1].src);
};

1 Comment

Negative. JSON index begins at 0.

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.