Group by/order by On JSON data using javascript/jquery

前端 未结 3 1210
滥情空心
滥情空心 2020-12-29 17:14

I have a JSON data and I need to do something like group by and i asked this question before here but i am not getting any satisfied answer so this time i would like to expl

3条回答
  •  青春惊慌失措
    2020-12-29 17:25

    There is no built-in "group by" or "order by" in Javascript for this scenario. You're going to have to do this manually. Something like this might help:

    var groups = myObject.Apps[0].groups;
    var authors = {};
    var authorNames = [];
    
    for(var i = 0; i < groups.length; i++) {
        var group = groups[i];    
    
        if(typeof authors[group.author] === "undefined") {
            authors[group.author] = [];
            authorNames.push(group.author);
            authorNames.sort();
        }
    
        authors[group.author].push({
            id: group.id,
            name: group.name,
            category: group.category
        });       
    }
    

    Usually in associative arrays you don't really care about the order of the keys and while iterating the order is usually not guaranteed. What I'm doing here is maintaining a separate array of names in sorted order. I can then iterate over that array and use those values to grab the associated object out of the associative array.

    Check out the fiddle.

提交回复
热议问题