Reputation: 471
I am using this API:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
I want to search this API for name based on its id.
In PHP it would look like this:
$id = 730; // input ID
$url = 'http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json';
$content = file_get_contents($url) ;
$data = json_decode($content, true);
$key = array_search($id, array_column($data['applist']['apps'], 'appid'));
echo $data['applist']['apps'][$key]['name'] // returns Counter-Strike: Global Offensive
Is it possible to replicate this process in JS? Or am I better off creating a second PHP file and accessing it with AJAX?
Upvotes: 0
Views: 104
Reputation: 2638
Pierre is correct that you can't do this from the browser because of cross-origin issues. You would have to proxy the request through to be able to get the data.
You could use PHP to fetch the data from steam, and then access it client side. With the data structure from steam you can get the item with your id using the find method on the array.
const data = {
applist: {
apps: [
{ appid: 1},
{ appid: 730, name: 'Needle' }
],
}
};
const id = 730;
const row = data.applist.apps.find(item => item.appid === id);
console.log(row); // { appid: 730, name: 'Needle' }
Upvotes: 1
Reputation: 607
Sure, you can see the answer of this question: Get JavaScript object from array of objects by value of property
But i think you'll have cross-origin issues if you do it in browser:
Access to XMLHttpRequest at 'http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json'
has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
This steam API is blocking access from js in browser.
Upvotes: 2