Javascript Angular 2/ES6/基于特性过滤对象
我调用两个API来返回数据对象。然后对每一个进行遍历,并搜索它是否有值 我想检查这些obj中是否有一个vas值匹配 getdata(slug){ }Javascript Angular 2/ES6/基于特性过滤对象,javascript,angular,loops,ecmascript-6,Javascript,Angular,Loops,Ecmascript 6,我调用两个API来返回数据对象。然后对每一个进行遍历,并搜索它是否有值 我想检查这些obj中是否有一个vas值匹配 getdata(slug){ } this.pageobj是一个对象 这是postsobj 在两种反应中,他们都有一个属性“slug”。 我想检查this.postsobj或this.pageobj中是否有包含“slug”==“hello word”的对象,如果是,则返回我对象并存储在var this.content中 更新 export class PageSingl
this.pageobj是一个对象
这是postsobj
在两种反应中,他们都有一个属性“slug”。 我想检查this.postsobj或this.pageobj中是否有包含“slug”==“hello word”的对象,如果是,则返回我对象并存储在var this.content中 更新
export class PageSingleComponent implements OnInit {
page: Page;
pageobj:any;
postsobj:any;
pageobjCheck:any
postsobjCheck:any
pageSlug:any;
content =new Array<any>();
constructor( private _apiService: apiService, private route: ActivatedRoute ) { }
getdata(slug){
this._apiService.getPages().subscribe(data =>{
this.pageobj = data
this.content.push(_.filter(this.pageobj, { 'slug':' hello-world' }));
})
this._apiService.getPosts().subscribe(data =>{
this.postsobj = data;
this.content.push(_.filter(this.postsobj, { 'slug':' hello-world' }));
})
}
ngOnInit() {
this.route.params.forEach((params: Params) => {
// Get slug from the rout
let slug = params['pageslug'];
console.log('slug is catcheds', slug)
this.pageSlug = params['pageslug'];
this.getdata(slug)
// Run functions
//
});
}
}
导出类PageSingleComponent实现OnInit{
第页:第页;
pageobj:任何;
postsobj:任何;
pageobjCheck:有吗
postsobjCheck:有吗
pageSlug:任何;
content=新数组();
构造函数(私有_apiService:apiService,私有路由:ActivatedRoute){}
getdata(slug){
此._apiService.getPages().subscribe(数据=>{
this.pageobj=数据
this.content.push(u.filter(this.pageobj,{'slug':'helloworld}));
})
此._apiService.getPosts().subscribe(数据=>{
this.postsobj=数据;
this.content.push(u.filter(this.postsobj,{'slug':'helloworld}));
})
}
恩戈尼尼特(){
this.route.params.forEach((params:params)=>{
//从溃败中得到子弹
设slug=params['pageslaug'];
console.log('段塞被捕获',段塞)
this.pageslaug=params['pageslaug'];
这个.getdata(slug)
//运行函数
//
});
}
}
我想您应该使用
在传递给映射函数的回调函数中,您希望检查响应对象表单数组是否具有等于“hello world”的slug属性。您的代码如下所示:
var content = response.filter(obj => obj && obj.slug === 'hello-world');
我更喜欢使用lodash,如下所示
this.content =new Array<any>();
this.content.push(_.filter(this.pageobj, { 'slug':' hello-world' });
this.content.push(_.filter(this.postsobj, { 'slug':' hello-world' });
这可以在服务器端本身完成。。有什么理由在这里处理吗?我想你不需要这个。内容?我不需要你知道这意味着什么?对不起,阿拉文。两件事:1)我认为你在每次推完后都缺少一个“')。然后我可以定义如下的变量content=newarray();并且不需要这样做。content=new Array();很抱歉输入错误,如果不初始化数组,则无法推送数据。你将得到未定义的错误我得到一个空对象。我是否像上面在更新中发布的那样做对了?
this.content =new Array<any>();
this.content.push(_.filter(this.pageobj, { 'slug':' hello-world' });
this.content.push(_.filter(this.postsobj, { 'slug':' hello-world' });
getPages(){
return this.http.get(...)
.takeWhile(data=>{
if(data.slug ==== 'hello-world'){
return data;
}
})
}