javascript 过滤角 json 7
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53519642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter angular json 7
提问by lams
I'm starting an angular application 7, beginner angular. I'm making a call from an api (for example) and storing the result in localstorage. So far so good. After saving I need to make a filter in the field called pdv.
我正在开始一个角度应用程序 7,初学者角度。我正在从 api 进行调用(例如)并将结果存储在 localstorage 中。到现在为止还挺好。保存后,我需要在名为 pdv 的字段中创建一个过滤器。
I can not implement the filter the way it is, it says that the filter is not part of the viewers. Can you give me a tip?
我无法按原样实施过滤器,它说过滤器不是查看器的一部分。你能给我一个提示吗?
This is my code:
这是我的代码:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, startWith } from 'rxjs/operators';
const CACHE_KEY = 'httpSalesCache';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
repos;
constructor(http: HttpClient){
const path = 'http://www.mocky.io/v2/x';
this.repos = http.get<any>(path)
.pipe(map(data => data.items));
this.repos.subscribe(next => {
localStorage[CACHE_KEY] = JSON.stringify(next);
});
this.repos = this.repos.pipe(
startWith(JSON.parse(localStorage[CACHE_KEY] || '[]'))
)
}
}
This is the return of the call http:
这是调用http的返回:
{"items":[
{"pdv": 1,
"status": "a"
}]}
采纳答案by Teun van der Wijst
You can do so using TypeScript builtin filter()function. Source: https://www.tutorialspoint.com/typescript/typescript_array_filter.htm
您可以使用 TypeScript 内置filter()函数执行此操作。来源:https: //www.tutorialspoint.com/typescript/typescript_array_filter.htm
const data = {
"items": [
{
"pdv": 1,
"status": "a"
}]
};
const filterValue = 1;
const result = data.items.filter(element => {
return element.pdv === filterValue;
});
resultwill contain an array of all itemsthat contained the property pdvwith a value of 1;
result将包含一个items包含pdv值为 1的属性的所有数组;
EDIT, updated after your comment
编辑,在您发表评论后更新
EDIT 2I realised you dont need a variable to store the result, you can just update the observable
编辑 2我意识到你不需要一个变量来存储结果,你可以只更新 observable
filterValue = 1;
path = 'http://www.mocky.io/v2/x';
this.repos = http.get<any>(path).pipe(
map(data => {
data.items = data.items.filter(element => {
return element.pdv === filterValue;
});
}));
}

