我正在尝试从 json 文件中找到数组的位置。但是当我用 indexOf 尝试时,我不断得到 -1
我也尝试过解析它,但没有成功。
console.log(data.prices.market_hash_name.indexOf("AK-47 | Aquamarine Revenge (Factory New)"))
也不起作用 “未捕获的类型错误:无法读取未定义的属性 'indexOf'”
代码如下:
$.ajax({
url: 'prices.json',
dataType: 'json',
type: 'get',
contentType: "text/html; charset=UTF-8",
cache: false,
success: function(data){
$(data.prices)
console.log(data.prices.indexOf("AK-47 | Aquamarine Revenge (Factory New)"))
}
});
这里是json文件:
{
"status": "success",
"prices": [
{
"app_id": "730",
"context_id": "2",
"market_hash_name": "'Blueberries' Buckshot | NSWC SEAL",
"price": "1.44",
"pricing_mode": "market",
"skewness": "-0.01",
"created_at": 1609156019,
"icon_url": null,
"name_color": null,
"quality_color": null,
"rarity_color": null,
"instant_sale_price": null
},
{
"app_id": "730",
"context_id": "2",
"market_hash_name": "AK-47 | Aquamarine Revenge (Factory New)",
"price": "58.16",
"pricing_mode": "market",
"skewness": "0.09",
"created_at": 1609152514,
"icon_url": null,
"name_color": "D2D2D2",
"quality_color": "EB4B4B",
"rarity_color": null,
"instant_sale_price": "23.26"
},
{
"app_id": "730",
"context_id": "2",
"market_hash_name": "'Two Times' McCoy | TACP Cavalry",
"price": "0.86",
"pricing_mode": "market",
"skewness": "0.11",
"created_at": 1609166685,
"icon_url": null,
"name_color": null,
"quality_color": null,
"rarity_color": null,
"instant_sale_price": null
},
]
}
答案 0 :(得分:1)
Prices 是一个对象数组;您的 indexOf 调用正在搜索特定的属性值,因此如果没有其他帮助,它将无法找到它。有很多方法可以做到这一点,但这里有一个。
您可以使用过滤器在对象数组中搜索匹配项,如果找到则返回第一个匹配项的索引,如果未找到则返回 -1。
我在此处编写的函数 objIndexOf
接受要搜索的数组、要测试的对象属性以及您要搜索的值。
var json = {
"status": "success",
"prices": [
{
"app_id": "730",
"context_id": "2",
"market_hash_name": "'Blueberries' Buckshot | NSWC SEAL",
"price": "1.44",
"pricing_mode": "market",
"skewness": "-0.01",
"created_at": 1609156019,
"icon_url": null,
"name_color": null,
"quality_color": null,
"rarity_color": null,
"instant_sale_price": null
},
{
"app_id": "730",
"context_id": "2",
"market_hash_name": "AK-47 | Aquamarine Revenge (Factory New)",
"price": "58.16",
"pricing_mode": "market",
"skewness": "0.09",
"created_at": 1609152514,
"icon_url": null,
"name_color": "D2D2D2",
"quality_color": "EB4B4B",
"rarity_color": null,
"instant_sale_price": "23.26"
},
{
"app_id": "730",
"context_id": "2",
"market_hash_name": "'Two Times' McCoy | TACP Cavalry",
"price": "0.86",
"pricing_mode": "market",
"skewness": "0.11",
"created_at": 1609166685,
"icon_url": null,
"name_color": null,
"quality_color": null,
"rarity_color": null,
"instant_sale_price": null
},
]
};
function objIndexOf(arr, key, value)
{
var matches = arr.filter(x => x[key] == value);
if(matches.length <= 0) return -1;
return arr.indexOf(matches[0]);
}
console.log(objIndexOf(json.prices, "market_hash_name", "AK-47 | Aquamarine Revenge (Factory New)"));
console.log(objIndexOf(json.prices, "market_hash_name", "blah"));