代码改变世界

Javascript中实现JSON数组多键值排序

2011-06-20 15:58  何朝阳  阅读(3066)  评论(0编辑  收藏  举报

在某项目中,需要实现用户自定义菜单的显示顺序,以及某项菜单是否显示,摸索了很久,最后找到了一个自己比较满意的思路:

①首先在后台使用C#获取数据库中的菜单数据,生成一个包含菜单数据项的JSON数组(由于某种原因没有使用SQL中的ORDER BY),如下:

var menuData1=[
{"orderid":-10,"text":"主页","title":"个人网站主页","url":"Default.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":10,"text":"个人新闻","title":"个人新闻","url":"News.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":5,"text":"发表论文","title":"发表论文","url":"Paper.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":2,"text":"出版专著","title":"出版专著","url":"Monograph.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":7,"text":"参与项目","title":"参与项目","url":"Project.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":8,"text":"个人荣誉","title":"个人荣誉","url":"Prize.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":1,"text":"发明专利","title":"发明专利","url":"Patent.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":0,"text":"文件共享","title":"文件共享","url":"FileShare.aspx?TeacherID=153","visible":true,"target":"_self"}
];

②这时需要先将数组按orderid升序排序,注意,sort方法会改写原来的数组:

menuData1.sort(function(a, b) { return a.orderid > b.orderid ? 1 : -1;} );//升序

③经过排序后,结果为:

menuData1=[
{"orderid":-10,"text":"主页","title":"个人网站主页","url":"Default.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":0,"text":"文件共享","title":"文件共享","url":"FileShare.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":1,"text":"发明专利","title":"发明专利","url":"Patent.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":2,"text":"出版专著","title":"出版专著","url":"Monograph.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":5,"text":"发表论文","title":"发表论文","url":"Paper.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":7,"text":"参与项目","title":"参与项目","url":"Project.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":8,"text":"个人荣誉","title":"个人荣誉","url":"Prize.aspx?TeacherID=153","visible":true,"target":"_self"},
{"orderid":10,"text":"个人新闻","title":"个人新闻","url":"News.aspx?TeacherID=153","visible":true,"target":"_self"}
];

④然后根据menuData1[i].visible属性,将可视菜单项显示出来(其中String.Format见《在Javascript中实现类似C#中string.Format的功能》一文):

    var menuString = "<ul><li class=\"menuDiv\"></li>";
    for(var i=0;i<menuData1.length;i++) {
        if(menuData1[i].visible) {
            menuString += String.Format("<li><a title=\"{0}\" class=\"menuA\" onfocus=\"this.blur()\" href=\"{1}\" target=\"{2}\">{3}</a></li><li class=\"menuDiv\"></li>", menuData1[i].title, menuData1[i].url, menuData1[i].target, menuData1[i].text);
        }
    }
    menuString += "</ul>";
    $(menuContainer).innerHTML = menuString;