我有以下JSFiddle我试图根据他们远离我的距离将一个json的口袋妖怪数据字符串排序成两个数组。
var pokemon = JSON.parse(JSONoriginal); //*See JSFiddle link for full JSON String*
//encounter_ids are unique to each spawned pokemon, use these to look for & remove duplicates
for(var x=0; x <= pokemon.result.length-1; x++){
var aPokemon = {
name: pokemon.result[x].pokemon_id,
encounter_id: pokemon.result[x].encounter_id,
expiration_timestamp_ms: pokemon.result[x].expiration_timestamp_ms,
latitude: pokemon.result[x].latitude,
longitude: pokemon.result[x].longitude
};
if(pokemon.result[x].expiration_timestamp_ms === undefined){
//Check if pokemon's already been put into nearby array, if so then we don't need to do anything
var a = nearby.filter(function(a){
return a.encounter_id === aPokemon.encounter_id;
})[0];
if(a === undefined){
//Put in nearby Array because we don't have a location
nearby.push(aPokemon);
}
}else{
//Check if pokemon's already been put into nearby array, if so then remove it from there
var b = nearby.filter(function(b){
return b.encounter_id === aPokemon.encounter_id;
})[0];
if(b !== undefined){
nearby.splice(nearby.indexOf(b),1);
}
//Check if pokemon's already been put into immediate array, if so then we don't need to do anything
var c = immediate.filter(function(c){
return c.encounter_id === aPokemon.encounter_id;
})[0];
if(c === undefined){
//Put it in immediate Array because we can locate & display them
immediate.push(aPokemon);
}
}
}
我能够解析我的示例json字符串并填充我的两个数组,但似乎某些pokemon不会从Nearby[]
数组中移除(当它们被放入Immediate[]
数组)。任何人都可以在我的逻辑中发现错误吗?如何让这个循环正常工作?
答案 0 :(得分:1)
所以Rattata,Krabby和Squirtle在附近的部分中不应出现那些ID?问题是如果有expiration_timestamp_ms
,你只检查重复项,而第二项没有。{/ p>
[编辑]
这应该可行:当将条目推送到附近时,检查条目是否已存在于直接阵列中。我已更新您的JSFiddle:
var a = nearby.filter(function(a){
return a.encounter_id === aPokemon.encounter_id;
})[0] || immediate.filter(function(c){
return c.encounter_id === aPokemon.encounter_id;
})[0];