2016-02-25 22 views
0

我只是關於創建一個網站,其中im遍歷JSON文件中的項目列表。它看起來像這樣:在Javascript中比較具體的結果/ jquery

"prices" : [ 
{ 
    "market_hash_name" : "★ Bayonet", 
    "price" : 141.04, 
    "created_at" : 1455877920 
}, 
{ 
    "market_hash_name" : "AWP | Pit Viper (Minimal Wear)", 
    "price" : "1.83", 
    "created_at" : 1455878005 
} 
. 
. 
. and so on 

現在,我在尋找,並通過了「market_hash_name」以$阿賈克斯和$每個組合由jQuery函數選擇「價格」 sucessfull。那就是:

$.ajax({url: "../json/priceapi.json", success: function(result){ // Get JSON File 

$.each(result.prices, function(i, v) {  
    if (v.market_hash_name == market_hash_name) { ... // Parse JSON Data 

一切工作正常,代碼似乎是好的,但問題是,有,在這個巨大的JSON文件的任何地方是完全相同的第二個「market_hash_name」但有額外的文本部分。例如:

{ 
    "market_hash_name" : "Souvenir AWP | Pit Viper (Minimal Wear)",        
    "price" : "102.18", // Additional text "Souvenir" 
    "created_at" : 1455878414 
}, 

由於這個「雙標籤」,$ each函數告訴我,對於一個鍵有兩個結果。我只想得到確切的結果。你有什麼想法如何做到這一點?有沒有辦法做這樣的事情?

$.each(result.prices, function(i, v) {  
    if (v.market_hash_name - "Souvenir" == market_hash_name) { ... 
+0

爲什麼你減去字符串從字符串?這是不正確的:''「字符串」 - 「字符串」' –

+0

「紀念品AWP |坑Vi蛇(略有磨損)」不等於「AWP |坑Vi蛇(略有磨損)」,這裏還有別的事情要做。 –

+0

@marcos你是對的,它僅僅是對可能的解決方案的輕描淡寫。 –

回答

0

感謝briosheje! https://jsfiddle.net/briosheje/f68wfet6/1/工程不錯!需要一點,但我工作:)

var res = { 
    "prices": [] 
}; 

$.each(json.prices, function(i, e) { 
    var exists = false; 
    $.each(res.prices, function (c, f){ 
    console.log(f.market_hash_name + " <> " + e.market_hash_name); 
    console.log(f.market_hash_name == e.market_hash_name); 
    if (("Souvenir " + f.market_hash_name) == e.market_hash_name) { 
     exists = true; 
    } 
    }); 

    !exists && res.prices.push(e); 
}); 

console.log(res); 
+0

小心大JSON文件和很多請求在短時間內 –

+0

我必須等待19個小時... –