最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript or jquery: Looping a multidimensional object - Stack Overflow

programmeradmin1浏览0评论

I just started playing around with JSON and I have created this example.

var shows = {

    "ShowA": 
                {   "Date"      : "November 3-5, 2011",
                    "Phone"     : "111-111-1111",
                    "Location"  : "some location",
                    "url"       : ""
                },

    "ShowB": 
                {   "Date"      : "January 15-18, 2012",
                    "Phone"     : "222-222-2222",
                    "Location"  : "another location",
                    "url"       : ""
                }

};

I figured out how to access each bit of information...ie: alert(shows.ShowA.Date);

However, I can't figure out how to loop the entire shows object in order alert each show and each show's properties. Do I need to change it to an array?

Any help would be greatly appreciated.

I just started playing around with JSON and I have created this example.

var shows = {

    "ShowA": 
                {   "Date"      : "November 3-5, 2011",
                    "Phone"     : "111-111-1111",
                    "Location"  : "some location",
                    "url"       : "http://www.showA.com"
                },

    "ShowB": 
                {   "Date"      : "January 15-18, 2012",
                    "Phone"     : "222-222-2222",
                    "Location"  : "another location",
                    "url"       : "http://www.showB.com"
                }

};

I figured out how to access each bit of information...ie: alert(shows.ShowA.Date);

However, I can't figure out how to loop the entire shows object in order alert each show and each show's properties. Do I need to change it to an array?

Any help would be greatly appreciated.

Share Improve this question asked Sep 7, 2011 at 20:20 kdubkdub 7672 gold badges10 silver badges19 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 14

you can use a for ... in loop:

for(var key in shows) {
    if (shows.hasOwnProperty(key)) {
        alert(shows[key].Date);
    }
}

It's important to note that an object has no sort order, but an array does. So if you wanted to sort by dates, you would need to use an array.

Also it's good practice to use Object.hasOwnProperty

for(show in shows){
     console.log(shows[show]);
}

Fiddle: http://jsfiddle.net/maniator/Wp3N9/

No extra libraries needed ^_^

发布评论

评论列表(0)

  1. 暂无评论