【发布时间】:2017-05-05 10:56:08
【问题描述】:
我需要从数组中过滤特定对象。 我在 json 文件中有多个这样的数组。
"functies":["zandbak", "voetbal", "petanque", "speeltoestellen", "basketbal"],
我们需要为 json 文件中的每个对象过滤数组的每个元素。
Javascript 代码
ready(function () {
var App = {
"init": function () {
this.URLSPEEL = './data/speelterrein.json'; // Cache the url with random users in variable URLRANDOMUSERME
this.loadDataSpeel(); // Load SPEEL Data
},
"loadDataSpeel": function () {
//1. Create a XMLHttpRequest object (Send to and load data from a WebAPI)
var xhr = typeof XMLHttpRequest != undefined
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
//2. Declare the type of the response
xhr.responseType = 'json';
//3. Listen to the changes in states within the connection
xhr.onreadystatechange = function () {
switch (xhr.readyState) {
case 0:
console.log('UNSENT');
break;
case 1:
console.log('OPENED');
break;
case 2:
console.log('HEADERS RECEIVED');
console.log(this.getAllResponseHeaders());
break;
case 3:
console.log('LOADING');
break;
case 4:
default:
console.log('LOADED');
//If status equals 200 then everything is ok else nok
if (xhr.status == 200) {
console.log('OK');
//Get the received data --> response
var data = (!xhr.responseType) ? JSON.parse(xhr.response) : xhr.response;
var speelterreinen = data.speelterreinen, n = speelterreinen.length, speelterrein = null;
var tempString_2 = "";
for (var i = 0; i < n; i++) {
speelterrein = speelterreinen[i];
console.log(speelterrein.length);
tempString_2 += '<div id="speelterrein_id" class="card blue-grey darken-1 z-depth-2">';
tempString_2 += '<div class="card-content white-text">';
tempString_2 += '<span class="card-title" >' + speelterrein.naam;
tempString_2 += '</span>';
tempString_2 += '<h5>Functies</h5><p>' + speelterrein.functies;
tempString_2 += '<div class="card-action"><a target="_blank" class="waves-effect waves-light btn" href="' + speelterrein.plaats;
tempString_2 += '">Locatie</a>';
tempString_2 += '</div></div></div>';
console.log(speelterrein.functies);
document.getElementById("speelterrein_id").innerHTML = tempString_2;
}
} else {
console.log(Error(xhr.status));
}
break;
}
};
//4. Open the connection or tunnel to the resource on the url
xhr.open('GET', this.URLSPEEL, true);
//5. Make the request to the specified resource
xhr.send(null);
}
};
App.init();
});
示例 json 文件
{"speelterreinen":[
{
"naam": "Sint-Baafskouterpark",
"functies": ["avontuurlijk spelen", "zandbak", "speeltoestellen"],
"coördinaten": "51.0568047,3.7551683",
"gemeente": "Sint-Amandsberg"
},
{
"naam": "Wasstraat speelterrein",
"functies":["zandbak", "voetbal", "petanque", "speeltoestellen", "basketbal"],
"coördinaten": "51.0553976,3.7442046",
"gemeente": "Sint-Amandsberg"
},
{
"naam": "Azaleastraat buurtpark",
"functies":["zandbak", "petanque", "speeltoestellen", "basketbal"]
"coördinaten": "51.0600225,3.7498565",
"gemeente": "Sint-Amandsberg"
},
【问题讨论】:
-
你的问题不清楚。请重新构图
-
那么,最后,给定“滚球”,您想要一个可以玩滚球的地方列表吗?
-
@georg 确实如此
标签: javascript html arrays json lodash