按条目值排序JSON

时间:2015-01-11 23:03:12

标签: javascript jquery json sorting

我正在尝试对某些JSON进行排序,以创建仅显示某些行的数据列表。我有一些代码以我想要显示的方式显示数据,它不是按照我想要的方式排序。以下是预先排序数据的工作代码:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<style type="text/css"> 
.items {display:table;list-style:none;margin:0;padding:0;border-spacing:5px;}
.items li {display:table-row;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;border:1px solid #ccc;padding:5px;margin:0 0 10px 0;}
.items li img {display:table-cell;vertical-align:top;width:160px;height:120px;}
.items li span.meta {display:table-cell;vertical-align:top;margin:0;padding:0 0 0 5px;font-size:6;}
.items li {margin:0 0 5px 0;}
</style>
<button onclick="mySearch()" type="button">Search</button>
<button onclick="myErase()" type="button">Clear Results</button>
<div id="home-list"></div> 
<script type="text/javascript"> 
function mySearch() {   
$('.items').remove();

//source file is https://docs.google.com/spreadsheet/ccc?key=1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2   

$(function listHomes() {    

$.getJSON( "https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values?alt=json-in-script&callback=?",

//this is the data that I wish to sort
function (data) {

    $('div#home-list').append('<ul class="items"></ul>');

    $.each(data.feed.entry, function(i,entry) { 

        var item = '<span style="display:none">' + entry.id.$t + '</span>'; 

        item += '<img src="http://img.paragonrels.com/ParagonImages/Listings/P2/CGMLS/' + entry.gsx$mls.$t + '/0/960/720/4d8fbda25ff383c57b907de4c08a8677/CGMLS' + entry.gsx$mls.$t + '.JPG"/>';

        item += '<span class="meta"><a href="http://www.bevhicksrealtor.com/home/search-my-listings/' + entry.gsx$mls.$t + '"><font size="3"><b>' + entry.title.$t + '</b></font></a>'; 

        item += '<br/>City: ' + entry.gsx$city.$t;  

                    item += '<br/>Bedrooms: ' + entry.gsx$beds.$t;  

        if (entry.gsx$subdivision.$t) { 

            item += '<br/>Description: ' + entry.gsx$subdivision.$t;    
        }   
        $('.items').append('<li>' + item + '</span></li>'); 

        });
    });
});
};
function myErase() {
$('.items').remove();
};
</script>

这是JSON

// API callback
JSONP({"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/","xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended","id":{"$t":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values"},"updated":{"$t":"2015-01-08T04:27:29.693Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Source Page"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"https://docs.google.com/spreadsheets/d/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/pubhtml"},{"rel":"http://schemas.google.com/g/2005#feed","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values"},{"rel":"http://schemas.google.com/g/2005#post","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values"},{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values?alt\u003djson-in-script"}],"author":[{"name":{"$t":"joshuam.hess"},"email":{"$t":"joshuam.hess@yourkickstart.org"}}],"openSearch$totalResults":{"$t":"4"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values/cokwr"},"updated":{"$t":"2015-01-08T04:27:29.693Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"303 Tarpon Trace \u003cbr\u003eByron, GA 31008"},"content":{"type":"text","$t":"mls: 122445, state: GA, county: Bibb County, city: Macon, subdivision: None, high: Northside, beds: 4, baths: 3, price: 250000, cars: 3"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values/cokwr"}],"gsx$address":{"$t":"303 Tarpon Trace \u003cbr\u003eByron, GA 31008"},"gsx$mls":{"$t":"122445"},"gsx$state":{"$t":"GA"},"gsx$county":{"$t":"Bibb County"},"gsx$city":{"$t":"Macon"},"gsx$subdivision":{"$t":"None"},"gsx$high":{"$t":"Northside"},"gsx$beds":{"$t":"4"},"gsx$baths":{"$t":"3"},"gsx$price":{"$t":"250000"},"gsx$cars":{"$t":"3"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values/cpzh4"},"updated":{"$t":"2015-01-08T04:27:29.693Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"104 Gretta Court \u003cbr\u003eWarner Robins, GA 31088"},"content":{"type":"text","$t":"mls: 122444, state: GA, county: Bibb County, city: Macon, subdivision: None, high: Bibb-Westside, beds: 3, baths: 2, price: 200000, cars: 2"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values/cpzh4"}],"gsx$address":{"$t":"104 Gretta Court \u003cbr\u003eWarner Robins, GA 31088"},"gsx$mls":{"$t":"122444"},"gsx$state":{"$t":"GA"},"gsx$county":{"$t":"Bibb County"},"gsx$city":{"$t":"Macon"},"gsx$subdivision":{"$t":"None"},"gsx$high":{"$t":"Bibb-Westside"},"gsx$beds":{"$t":"3"},"gsx$baths":{"$t":"2"},"gsx$price":{"$t":"200000"},"gsx$cars":{"$t":"2"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values/cre1l"},"updated":{"$t":"2015-01-08T04:27:29.693Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"112 Derringer Court \u003cbr\u003eByron, GA 31008"},"content":{"type":"text","$t":"mls: 120081, state: GA, county: Bibb County, city: Macon, subdivision: Woolfolk, high: See Remarks, beds: 2, baths: 2, price: 150000, cars: 1"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values/cre1l"}],"gsx$address":{"$t":"112 Derringer Court \u003cbr\u003eByron, GA 31008"},"gsx$mls":{"$t":"120081"},"gsx$state":{"$t":"GA"},"gsx$county":{"$t":"Bibb County"},"gsx$city":{"$t":"Macon"},"gsx$subdivision":{"$t":"Woolfolk"},"gsx$high":{"$t":"See Remarks"},"gsx$beds":{"$t":"2"},"gsx$baths":{"$t":"2"},"gsx$price":{"$t":"150000"},"gsx$cars":{"$t":"1"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values/chk2m"},"updated":{"$t":"2015-01-08T04:27:29.693Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"105 Kennedy Court \u003cbr\u003eWarner Robins, GA 31093"},"content":{"type":"text","$t":"mls: 116141, state: GA, county: Macon County, city: Oglethorpe, subdivision: See Remarks, high: See Remarks, beds: 1, baths: 1, price: 50000, cars: 1"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/1z7X-IvfauqyWul4oh_46e471nNt13ZpNhyXSIm_NXKI/ow6ewk2/public/values/chk2m"}],"gsx$address":{"$t":"105 Kennedy Court \u003cbr\u003eWarner Robins, GA 31093"},"gsx$mls":{"$t":"116141"},"gsx$state":{"$t":"GA"},"gsx$county":{"$t":"Macon County"},"gsx$city":{"$t":"Oglethorpe"},"gsx$subdivision":{"$t":"See Remarks"},"gsx$high":{"$t":"See Remarks"},"gsx$beds":{"$t":"1"},"gsx$baths":{"$t":"1"},"gsx$price":{"$t":"50000"},"gsx$cars":{"$t":"1"}}]}});

我想通过几个JSON条目(床,浴室等)对信息进行排序。我已经尝试了很多东西但还没有得到结果。我甚至尝试使用查询在电子表格中对数据进行排序,但我认为我无法获得有效的JSON响应。

1 个答案:

答案 0 :(得分:1)

对于排序,我将使用Lodash。对于那些想要它的人,我也会在纯JS中发布相同的解决方案。我们需要关注的第一件事是按顺序获取密钥列表。所以,让我们从测试对象开始。我只想扔掉一些随机的字段/类型:

var obj= {  
    test : 5,
    colour : 'red',
    song : 'I Believe In A Thing Called Love',
    profession : 'Singer',
    gender : 'Male',
    languages : {
        array : [ 'French', 'German', 'English' ]
    },
    relationships : {
        'sister' : 'Jasmine',
        'brother' : 'Ryan'
    }
}

我们需要做的第一件事是访问对象内部的键列表。幸运的是,这很简单:

// Underscore
var keys = _.keys(object);
// → ['test', 'colour', 'song', 'profession', 'gender',     'languages', 'relationships']

// JavaScript
var keys = Object.keys(object);
// → ['test', 'colour', 'song', 'profession', 'gender', 'languages', 'relationships']  

首先要注意的是,这只会给我们提供顶级密钥。这是因为内部对象在技术上是不同的对象。如果我们在内部对象上调用上述任何一个,我们也会得到它们的键。

好的,我们现在有一个对象中的顶级键列表。当然,下一步是按字母顺序对这些键进行排序,这也非常简单。 Underscore有一个很好的方法可以实现这一点,这很容易,但在纯JS中实现它也很随意。

// Underscore
var sortedKeys = _.sortBy(keys, function(key){  
    return object[key]; 
});

// JavaScript
var sortedKeys = keys.sort(function(key1, key2){  
    var val1 = object[key1].toLowerCase();
    var val2 = object[key2].toLowerCase();

    if(val1 < val2 ) return -1;
    if(val1 > val2 ) return 1;
    return 0;
})

// Both → ['colour', 'gender', 'languages', 'profession', 'relationships', 'song', 'test']

最后:

var sortedObj = {};

// Underscore
_.each(keys, function(key) {  
    sortedObj[key] = object[key];
});

// JavaScript
for(var index in keys){  
    var key = keys[index];
    sortedObj[key] = object[key];
}

// Resulting object
{
    'colour': 'red',
    'gender': 'Male',
    'languages': {
        'array': [
            'French',
            'German',
            'English'
        ]
    },
    'profession': 'Singer',
    'relationships': {
        'sister': 'Jasmine',
        'brother': 'Ryan'
    },
    'song': 'I Believe In A Thing Called Love',
    'test': 5
}

如果内部对象也需要,我们只需检查对象类型,然后调用代码,如果它是一个对象:

if(typeof object[key] == 'object'){  
    sortedObj[key] = sortObject(object[key]); // sortObj will be the function holding this code
} else {
    sortedObj[key] = object[key];
}

Source