arrays - 以角度操作json数组
问题描述
如何从打字稿中的数组中打印特定值?我在打字稿中有以下代码:
import { AngularFirestore } from '@angular/fire/firestore';
export class ProfileComponent implements OnInit {
myArray: any[] = [];
constructor(public afs: AngularFirestore) {}
emailtoprint = "sadasd@assf.co";
test = this.afs.collection('doctors').get().subscribe((ss) => {
ss.docs.forEach((doc) => {this.myArray.push(doc.data()); });
});
}
emailtoprint 的电子邮件以 html 格式打印,如下所示:
<div *ngFor='let i of myArray'>
<div *ngIf="i.email == emailtoprint">{{i.email}}</div>
</div>
如您所见,我能够使用 ngIf 找到相应的电子邮件......虽然,如果 myArray 有很多值,它并不是真正的最佳选择。我想知道如何从打字稿角度的数组中获取特定值?我尝试了以下但我得到一个空的输出:
test3 = this.myArray.find(e => e.email === emailtoprint);
这是我做时为 myArray 找到的实体
<li *ngFor="let i of myArray">
{{i | json}}
</li>
{“名字”:“Df”,“姓氏”:“Sdf”,“电子邮件”:“sadasd@assf.co”}
{“名字”:“安娜”,“姓氏”:“模拟人生”,“电子邮件”:“医生@hotmail.com”}
{ "firstName": "John", "lastName": "Adad", "email": "nurse@hotmail.com" }
解决方案
您不能variable
在订阅的服务调用中分配一个。相反,您可以像这样实现它。
您可以使用以下任一方法:
方法#1
this.afs
.collection('doctors')
.get()
.subscribe(({ docs }) => {
// Replicating what you did by and invoking the data function
const data = docs.map(({ data }) => data());
// If you use .find() , it will give you an object which you can't loop through
this.myArray = data.find(({ email }) => email === this.emailtoprint);
// or
// If you use .filter(), it will give you an array, but i say if finding only 1 data, it's best to use .find
this.myArray = data.filter(({ email }) => email === this.emailtoprint);
// Console to check the result
console.log(this.myArray);
});
方法#2
或者,如果您仍想获取原始数据数组并为电子邮件匹配使用单独的变量,则可以这样做:
userMatch: any;
...
.subscribe(({ docs }) => {
this.myArray = docs.map(({ data }) => data());
this.userMatch = this.myArray.find(({ email }) => email === this.emailtoprint);
// Console and check the data
console.log(this.myArray);
console.log(this.userMatch);
});