Brad Adams
Brad Adams

Reputation: 2079

Switch JSON key in for loop (jQuery)

I'm working with the Wordpress JSON API plugin, and custom fields.

Here's the relevant section of the JSON file:

{
  "post": {
    "custom_fields": {
      "tracks": [
        "4"
      ],
      "tracks_0_name": [
        "First Track"
      ],
      "tracks_1_name": [
        "Second Track"
      ],
      "tracks_2_name": [
        "Third Track"
      ],
      "tracks_3_name": [
        "Fourth Track"
      ]
    },
}

So immediately, I know how many tracks there are from the tracks key. I'm then running this (where trackCount = tracks):

for( var i = 0; i < trackCount; i++) {

    newTrack = '<li>';
    newTrack += '<div class="trackNum">'+(i+1)+'</div>';
    newTrack += '<span>';
    newTrack += result.post.custom_fields.tracks_X_name;
    newTrack += '</span>';
    newTrack += '</li>';

    $('.tracklist .main').append(newTrack);
}

That tracks_X_name needs to change each time based on the i variable, and I can't for the life of me figure out how. Any thoughts?

Note: The code is working, if I run this with tracks_0_name I get 4 tracks with the same title, but count, etc. is all fine. It's just a case of targeting the correct key on each instance of the loop.

Upvotes: 0

Views: 80

Answers (2)

Twisty
Twisty

Reputation: 30893

Moving my comment to an answer:

Switch to the index name:

newTrack += result.post.custom_fields["tracks_" + i + "_name"];

Hard to do with all Dot notation.

Upvotes: 1

shteeven
shteeven

Reputation: 532

The easy fix is to change the key from dot notation to something like this:

newTrack += result.post.custom_fields['tracks_'+i+'_name'];

However, I would recommend changing how you structure your data:

{
"post": {
    "custom_fields": {
      "tracks": [
        "4"
      ],
      "tracks_0_name": [
        "First Track"
      ],
      "tracks_1_name": [
        "Second Track"
      ],
      "tracks_2_name": [
        "Third Track"
      ],
      "tracks_3_name": [
        "Fourth Track"
      ]
    },
}

This method can cause errors or undesired behavior if the track count is different from the actual number of tracks. If I were to write this out, I would do it more like this:

{
  "post": {
    "custom_fields": [
      "tracks_0_name",
      "tracks_1_name",
      "tracks_2_name",
      "tracks_3_name"
    ]
  }
}

And for the JQuery:

var len = result.post.custom_fields.length;
for( var i = 0; i < len; i++) {

    newTrack = '<li>';
    newTrack += '<div class="trackNum">'+(i+1)+'</div>';
    newTrack += '<span>';
    newTrack += result.post.custom_fields[i];
    newTrack += '</span>';
    newTrack += '</li>';

    $('.tracklist .main').append(newTrack);
}

Upvotes: 1

Related Questions