2016-11-09 58 views
0

在排序數組後,我怎樣才能讓我的ID返回?通過JSON文件數組排序後取回ID?

var distance = [];

我環並添加ID和響應(響應是當前用戶位置和存儲位置之間的distace)到陣列距離:distance[item.properties.Nid] = response;

每個之後增加了新的距離排列,我再次對數組進行排序:

sort_stores = function(stores){ 
    stores = stores.filter(function(item){ 
     return item !== undefined; 
    }); 

    stores.sort(function(a, b){ 
     return a - b; 
    }); 

    console.log(stores); 
}; 

但我怎麼才能讓我的ID distance[item.properties.Nid]回來?當我將stores記錄到我的控制檯時,只有響應正在記錄。

回答

1

以不同方式組織數據,以便您的數據同時具有一個對象中的ID和距離。

所以,專賣店如下:

distance.push({ Nid: item.properties.Nid, distance: response }); 

而與此功能進行排序:

sort_stores = function(stores){ 
    // NB: first step (filter out undefined) is not needed anymore 
    stores.sort(function(a, b){ 
     return a.distance - b.distance; // add distance property 
    }); 

    console.log(stores); 
}; 

要獲得的距離,你可以做這樣的事情:

firstDistance = stores[0].distance; 

或環:

for (var store of stores) { 
    console.log('Store ', store.Nid, ' is at ', store.distance) 
} 
+0

謝謝,它的工作原理!但是一個簡單的問題,我現在如何才能記錄距離?我可以用'console.log(stores.distance)'來代替整個對象嗎? –

+1

不客氣。是的,你會得到這樣的距離,但是你需要指定:'stores [5] .distance'。它也是如何在* sort *回調函數中完成的。 – trincot

+1

我加了一些例子。 – trincot