【问题标题】:Compare exact result in Javascript/Jquery比较 Javascript/Jquery 中的确切结果
【发布时间】:2016-02-25 17:06:24
【问题描述】:

我只是要创建一个网站,在其中迭代 JSON 文件中的项目列表。它看起来像这样:

"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

现在,我通过 jquery 结合 $ajax 和 $each 函数,通过“market_hash_name”搜索和选择“价格”成功。这里是:

$.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) { ...

【问题讨论】:

  • 为什么要从一个字符串中减去一个字符串?这是不正确的:"string" - "string"
  • “Souvenir AWP | Pit Viper(略有磨损)”不等于“AWP | Pit Viper(略有磨损)”,这里还有其他事情。
  • @marcos 你是对的,它只是为了轻描淡写的一个可能的解决方案。
  • 您应该通过 ID 或类似名称来识别产品,并且它们不应该重复,这是您实际能够做的最好的(并且可能是最快的解决方案),以便实际能够比较项目。你能得到/编辑生成 json 文件的内容吗?
  • @DanielBeller :文字总是“纪念品”吗?如果是这样,这可能会对您有所帮助:jsfiddle.net/briosheje/f68wfet6/1。不是最好的,也不是最快的,但它解决了问题。

标签: javascript jquery json steam


【解决方案1】:

感谢 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);

【讨论】:

  • 注意大型json文件和短时间内大量请求
猜你喜欢
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 2012-10-30
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
相关资源
最近更新 更多