2015-01-11 5 views
0

일부 JSON을 정렬하여 특정 행만 표시되는 데이터 목록을 작성하려고합니다. 데이터를 표시하려는 방식으로 데이터를 표시하는 코드가 있습니다. 원하는대로 정렬되지 않았습니다. 여기항목 값으로 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":"[email protected]"}}],"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 응답을 다시 얻을 수 없다고 생각합니다.

+0

코드를 정리하십시오. 불필요한 부분은 없애고 문제가 정확히 어디로 향하는 지 알려줍니다. – Mouser

+0

Annnnd hwat는 JSON 모양을 사용합니까? – Hamish

답변

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로 구현하는 것도 매우 캐주얼합니다.

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

// 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 
} 

뿐만 아니라, 우리가 객체 유형에 대한 검사에 넣어 내부 개체에 대한 필요한 경우 다음 코드를 기억

Source