Reputation:
As another user in my other thread suggested to post another question here in regards to explaining how to access JSON Objects. The code I am using is:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$.getJSON(
"https://api.guildwars2.com/v1/wvw/matches.json",
function (data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
});
});
</script>
What I am trying to do with the JSON code, is to search through for a specified world_id
and return the match_id
. I'm very new to JavaScript so I'm not too sure how to do it, and how to access the stringified data which the code above gives me.
The way I figured how to do this, is to create an array and store each object in it, then loop through and check for a matching id like,
if(obj[i].red_world_id == 'xxxx' || obj[i].blue_world_id == 'xxxx' || obj[i].green_world_id == 'xxxx') {
return obj[i].wvw_match_id;
}
My only problem is I'm not sure how to set an array as the JSON data.
Upvotes: 1
Views: 1138
Reputation: 28114
There is no need to stringify, you could work with the JSON object directly:
function(data) {
var filteredArray=$.grep(data.wvw_matches, function (item) {
return (item.red_world_id == 'xxxx' || item.blue_world_id == 'xxxx' || item.green_world_id == 'xxxx');
});
}
See this page for information on jQuery.grep.
Upvotes: 0
Reputation: 3170
.use this code -
$(function() {
$.getJSON("https://api.guildwars2.com/v1/wvw/matches.json", function(
data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
var result = [];//for if it has many matches
for ( var i=0;i<data.wvw_matches.length;i++ ) {
var obj = data.wvw_matches[i];
if (obj.red_world_id == 'xxxx' || obj.blue_world_id == 'xxxx'
|| obj.green_world_id == 'xxxx') {
result.push(obj.wvw_match_id);
}
}
});
});
Upvotes: 1