【发布时间】:2021-03-19 20:03:14
【问题描述】:
我想知道防止重复数据进入新数组的最佳方法是什么。我有一个服务调用,它返回相同的数组 3 次。我正在尝试从数组中的对象内部获取一个数字并将它们相加以创建一个“总”数(fullRentAmt),但是由于该数组被返回了 3 次,所以我得到了总数 *3。我在想也许 .some() 或 .filter() 可以在这里使用,但我从未使用过这些/不确定如何在这里实现。感谢您的帮助!
我试过了,但它不起作用/新数组没有被填充:
组件
properties = [];
fullRentAmt: number = 0;
const propertyDataSub = this.mainService.requestPropertyData()
.subscribe((pData: PropertyData[]) => {
if (pData) {
const propertyData = pData;
for (let i = 0; i < propertyData.length; i++) {
if (this.properties[i].propertyId !== propertyData[i].propertyId) {
this.properties.push(propertyData[i]);
}
}
for (let i = 0; i < this.properties.length; i++) {
this.fullRentAmt += this.properties[i].tenancyInformation[0].rentAmount;
}
});
从后端返回的数据(2 个对象的数组):
[
{
"tenantsData":[
{
"email":null,
"tenantNames":null,
"propertyId":2481,
}
],
"tenancyInformation":[
{
"id":2487,
"rentAmount":1000,
}
],
},
{
"tenantsData":[
{
"email":null,
"tenantNames":null,
"propertyId":3271,
}
],
"tenancyInformation":[
{
"id":3277,
"rentAmount":1200,
}
],
},
【问题讨论】:
-
但是为什么后端会返回 3 次呢?这是来自 Angular 的 3 次请求吗?还是来自后端的错误?
标签: javascript json angular