Javascript 如何使用click函数提取和显示基于国家名称的特定JSON数据
我有如下JSON格式的数据Javascript 如何使用click函数提取和显示基于国家名称的特定JSON数据,javascript,json,angular,Javascript,Json,Angular,我有如下JSON格式的数据 const period: Data[] = [ { name: "Germany", id: 1, data: [ { date0: "2015-01-28", date1: "2015-02-04" }, { date0: "2015-08-27", date1: "2015-09-07" }, { date0: "2015-12-24", date1: "2016-01-05" } }, { name:
const period: Data[] = [
{
name: "Germany",
id: 1,
data: [
{ date0: "2015-01-28", date1: "2015-02-04" },
{ date0: "2015-08-27", date1: "2015-09-07" },
{ date0: "2015-12-24", date1: "2016-01-05" }
},
{
name: "France",
id: 2,
data: [
{ date0: "2015-01-28", date1: "2015-02-04" },
{ date0: "2015-08-27", date1: "2015-09-07" },
{ date0: "2015-12-24", date1: "2016-01-05" }
我可以在方法中调用服务来获取所有这些数据
{
this.admissionService.getAdmissions().subscribe(perioddata =>
{
this.admission = [perioddata]
)};
但是,我只希望通过实现onValueChanged($event)来获得基于国家名称的呼叫数据
onValueChanged(数据){
this.acmission.filter(['country','=',data.value]);
}
基本上,我的前端是,我从列表中选择一个国家,它应该根据国家名称调用数据。你能做到:
onValueChanged(event) {
const country = event.target.value;
this.admissionService.getAdmissions().pipe(
// get the object in concern (let's say the Germany slice)
map(countriesData => countriesData.find(countryData => countryData.name ===
country)),
// get the data array from the object in concern
map(countryData => countryData.data),
).subscribe(dataArrayForCountry => {
// do whatever you need, at this point I am just logging it.
console.log(dataForCountry);
});
}
如果您使用的是旧版本的RxJs,则应为:
this.admissionService.getAdmissions()
.map(countriesData => countriesData.find(countryData => countryData.name === country))
.map(countryData => countryData.data)
.subscribe(dataArrayForCountry => {
console.log(dataArrayForCountry);
});
如果方法
onValueChanged
的数据
是某个国家/地区,则可以过滤期间的数组:
onValueChanged(data) {
this.period.filter(f => f.name == data);
}
例如:
const period=[
{
名称:“德国”,
id:1,
数据:[
{date0:“2015-01-28”,date1:“2015-02-04”},
{date0:“2015-08-27”,date1:“2015-09-07”},
{date0:“2015-12-24”,date1:“2016-01-05”}
]
},
{
名称:“法国”,
id:2,
数据:[
{date0:“2015-01-28”,date1:“2015-02-04”},
{date0:“2015-08-27”,date1:“2015-09-07”},
{date0:“2015-12-24”,date1:“2016-01-05”}
]
}
];
事件=‘法国’;
const result=period.filter(f=>f.name==event);
控制台日志(结果)代码>是admissionService.filter
还是admissionService.admission.filter
?另外,您正在将一个$event
传递给onValueChanged
,因此函数应该如下所示:onValueChanged($event){this.admissionService.filter(['country','=',$event.target.value]);}
。注意$event.target.value
而不是$event.value
。谢谢我尝试了你的方法。我的数据是国家列表,但当我选择一个国家并从列表中选择法国时,结果数组为空onValueChanged(data){this.result=this.acmission.filter(f=>f.name==data.value);console.log(this.result);}
@Sam您能创建一个示例吗?@Sam它不工作。那么你能写console.log(data)
?@Sam和console.log(this.admission)
让我们看看。
onValueChanged(data) {
this.period.filter(f => f.name == data);
}