2013-07-19 39 views
0

我有這樣Javascript或JQuery的JSON對象分組

[ 
{"attributes":{"SHAPELEN":26.2293318917963,"CITYID":2061}}, 
{"attributes":{"SHAPELEN":16.9352548253636,"CITYID":2062}}, 
{"attributes":{"SHAPELEN":22.101151804600597,"CITYID":2063}}, 
{"attributes":{"SHAPELEN":22.8809188858315,"CITYID":2061}}, 
{"attributes":{"SHAPELEN":18.6906905910402,"CITYID":2063}}, 
{"attributes":{"SHAPELEN":31.322932493622,"CITYID":2062}}, 
{"attributes":{"SHAPELEN":10.5580020747299,"CITYID":2063}}, 
] 

一個JSON數據,並通過我和CITYID總和SHAPELENs這樣想這組數據。

[ 
{CITYID:2061, TOTAL=49.1}, 
{CITYID:2062, TOTAL=47.2}, 
{CITYID:2063, TOTAL=51,34} 
] 

我創建了一個javascript函數,但沒有工作,我想。

function gropData(data) { 
    var features = data.features; 
    var cities = []; 

    $.each(features, function (index, item) { 
     // **if cities not include item, add in cities. But if not working here** 
     if (!$.inArray(item.attributes, cities)) { 
      cities.push(item.attributes); 
     } 

    }); 
} 

有沒有你看到的解答?

+1

這是什麼'$ inArray(item.attributes,市)'該怎麼辦!?另外'$ .inArray'返回一個索引,所以如果你想檢查重複的,你應該做的'$ .inArray == -1' –

回答

0

$.inArray()是一個可怕的命名功能。它不會返回一個布爾值,如果在數組中找到它,它將返回該項目的索引,如果該項目未找到,則返回-1。所以如果找不到物品,檢查真實性將會返回true。如果該項目是數組中的第一個,則它將評估爲false。

你需要做這個:

if ($.inArray(item.attributes, cities) < 0) { 
    // item not found 
    cities.push(item.attributes); 
} 

if ($.inArray(item.attributes, cities) == -1) {也適用,如果這是您更容易閱讀/理解。

0

您不能搜索的對象值的數組,您可能需要遍歷數組來檢查每個對象手動或使用jQuery的$ .grep功能。另外,上面的JSON對象中不存在data.features,您可能只想對數據本身執行$ .each。

var result = $.grep(cities, function(e){ return e.CITYID == item.attributes.CITYID; }); 
    if(result.length == 0){ 
     var tempItem = { CITYID : item.attributes.CITYID, TOTAL : item.attributes.SHAPELEN }; 
     cities.push(tempItem); 
    }else{ 
     result[0].TOTAL += item.attributes.SHAPELEN; 
    } 
+0

這是玩小提琴:[鏈接] http://jsfiddle.net/ xmTNW / – verbanicm

0

也是一個純JavaScript版本:

function groupData(data) { 
    var cities = []; 
    data.forEach(function(datum) { 
    var cityEntry, 
     attr = datum.attributes; 
    cities.some(function(city) { 
     if (city.CITYID === attr.CITYID) { 
     cityEntry = city; 
     return true; 
     }}); 

    if (cityEntry) { 
     cityEntry.TOTAL += attr.SHAPELEN; 
    } else { 
     cities.push({CITYID: attr.CITYID, 
        TOTAL: attr.SHAPELEN}); 
    } 
    }); 
    return cities; 
} 
相關問題