代码之家  ›  专栏  ›  技术社区  ›  nielsv

分析数据并在字母下按字母顺序排列

  •  0
  • nielsv  · 技术社区  · 13 年前

    这就是我想要成为的:

    enter image description here

    这是我的javascript:

    var retrievedObject = localStorage.getItem('exhibitor');
    
        // CALL FUNCTION
        parsePerObject(JSON.parse(retrievedObject));
    
        function parsePerObject(data){
    
        }
    

    这是我在本地存储中的对象:

    {“41873”:{“id”:“41873 Vroman“,”shortname“:”“,”booth“:” 尤特·祖尔特。“,”电话“:”0497841121“,”地址“:”Drogenboomstraat 54”,“电子邮件”:“vroman.niels@hotmail.com“,”网页“:” http://nielsvroman.be “,”代码“:”“,”用户名“:”“image8”:“”,“imagedescription8”:image11“:”“,”imagedescription11“:“,”imagedescription19“:”“,”image_20“:”categories“:[],”linktodetails“:true,”imagethumb“:”},”41877“:{”id“:”41877”,“external_id”:“”,“eventid”: Daems“,”shortname“:”“,”booth“:”,”imageurl“:” Daems”,“电话”:“0497683697”,“地址”:“仓库”,“电子邮件”:“fer.dau@gmail.com“,”网页“:” http://ferdau.be “,”代码“:”“,”用户名“:”“image8”:“”,“imagedescription8”:image11“:”“,”imagedescription11“:“,”imagedescription19“:”“,”image_20“:”categories“:[],”链接详细信息“:true}}

    有人知道我如何按字母顺序对名字进行排序,并从第一个字母开始制作标题吗?

    1 回复  |  直到 10 年前
        1
  •  2
  •   GardenRouteGold    12 年前

    假设你有 Array 的对象,而不是 Object 对象,以启用索引和排序。对象没有顺序。

    您从中检索 localStorage 。你解析它。

    var people = JSON.parse(localStoarge.getItem("exhibitor");
    // now you have an array of objects, each object representing a person.
    // regardless of what structure you have now, change it to achieve this.
    var comparePersons = function(a, b) {
        // this function will compare two people objects.
        return a.name.localeCompare(b.name);
        // it's using String.prototype.localeCompare which returns 1 if a.name > b.name,
        // 0 for equal and -1 for smaller. localeCompare is lexicographic comparison.
    };
    people.sort(comparePersons);
    // now you have the people sorted alphabetically.
    

    您可以遍历people数组,获取唯一的起始字母,用它们组成一个数组,然后根据需要显示数据。它应该相当简单。

    var letters = '', groups = {};
    for (var i = 0, len = people.length; i < len; i++) {
         var letterKey = people[i].name.charAt(0).toLowerCase();// get the first letter
         if (letters.indexOf(letterKey)) == -1) {
             letters += letterKey;
             groups[letterKey] = [people[i]];// index the people by unique letters.
         } else {
             groups[letterKey].push([people[i]]);// add to the existing list. Another Syntax fix
         };
    };
    

    在这一点上,您有一个这样的对象:

    a: [person1, person2, person5, etc..]//the people at A.
    b: [person 3, person 4, etc..]// the people at B.
    

    只需使用以上数据即可创建显示。再多的话,我就得给你开发票:)。

    这里的技巧是 Array.prototype.sort ( here is more on it )以及 String.prototype.localeCompare ( read more here ).