Mike
Mike

Reputation: 118

json parsing in javascript with find length and switch with index value

"slider":
[{
    "album":{
        "name":"album 0",
        "title":"title 0",
        "description":"desc 0"
    },
    "album":{
        "name":"album 1",
        "title":"title 1",
        "description":"desc 1"
    },
    "album":{
        "name":"album 2",
        "title":"title 2",
        "description":"desc 2"
    }
  }]
}

I want to find the length of the albums and I wanted to switch to the album with index value.

please help me...

Upvotes: 0

Views: 172

Answers (3)

mplungjan
mplungjan

Reputation: 178350

If you have

var slider= {
  "albums": [ 
    {
        "name":"album 0",
        "title":"title 0",
        "description":"desc 0"
    },
    {   "name":"album 1",
        "title":"title 1",
        "description":"desc 1"
    },
    {
        "name":"album 2",
        "title":"title 2",
        "description":"desc 2"
    }
  ]
}

then slider.albums[1].name will give you "album 1"


UPDATE So in a for loop:

var albums = slider.albums;
for (var i=0,n=albums.length, album;i<n;i++) { 
  album = albums[i];
  alert((i+1)+":"+album.name+" - " + album.title);
}

DEMO

Upvotes: 1

richardaday
richardaday

Reputation: 2874

The way you are modeling your JSON is incorrect. Currently you have 3 keys that all have the same identifier (album). You should instead change that into an array.

Here's a good example on how to do this:

var slider = {
    "albums":
    [
        {
            "name":"album 0",
            "title":"title 0",
            "description":"desc 0"
        },
        {
            "name":"album 1",
            "title":"title 1",
            "description":"desc 1"
        },
        {
            "name":"album 2",
            "title":"title 2",
            "description":"desc 2"
        }
    ]
}

slider.albums.length

Upvotes: 0

inhan
inhan

Reputation: 7470

I would go about picking a structure rather like:

"slider":[
    {
        "name":"album 0",
        "title":"title 0",
        "description":"desc 0"
    },
    {
        "name":"album 1",
        "title":"title 1",
        "description":"desc 1"
    },
    {
        "name":"album 2",
        "title":"title 2",
        "description":"desc 2"
    }
]

Upvotes: 0

Related Questions