我有以下对象列表:
var data = [
{
"AcctId": 100,
"Value": true
},
{
"AcctId": 200,
"Value": false
}
]
我想这样选择不同的AcctId:
Output: [100, 200]
我尝试使用角度滤镜方法:
var newData = data.filter(r => r.AcctId);
但是,它返回的列表与输入相同。有人可以指导我做错什么吗?
答案 0 :(得分:3)
尝试这样:
this.result = Array.from(new Set(this.data.map(x => x.acctId)));
或
constructor() {
this.result = this.GetDistinctValues(this.data, "acctId").map(x => x.acctId);
}
GetDistinctValues(Source: Array<any>, FilterKey: string = null): Array<any> {
let DistinctArray = [];
try {
Source.forEach(e => {
if (FilterKey !== null && FilterKey !== undefined && FilterKey !== "") {
if (
DistinctArray.filter(DE => DE[FilterKey] === e[FilterKey]).length <=
0
)
DistinctArray.push(e);
} else {
if (DistinctArray.indexOf(e) === -1) DistinctArray.push(e);
}
});
} catch (error) {
DistinctArray = [];
}
return DistinctArray;
}
答案 1 :(得分:0)
或者lodash方式:
lodash.uniq(this.data.map(x => x.acctId));
答案 2 :(得分:0)
您可以使用rxjs库
import { of } from 'rxjs';
import { distinct } from 'rxjs/operators';
interface Person {
age: number,
name: string
}
of<Person>(
{ age: 4, name: 'Foo'},
{ age: 7, name: 'Bar'},
{ age: 5, name: 'Foo'},
).pipe(
distinct((p: Person) => p.name),
)
.subscribe(x => console.log(x));