【发布时间】:2020-09-29 22:24:00
【问题描述】:
我有一个名为“infos”的对象数组,在这个对象数组中我有一个名为 TagId 的元素。我有另一个名为“TagIds”的数组,它在任何给定时间都包含 0-3 个 ID。我想遍历我的“infos”数组中的每个对象,如果有匹配项,则将该对象添加到我的“filteredResults”数组中。
现在我通过以下代码实现了这一点:
infos: Array<{InfoPageId: number, DepartmentId: number, Name: string, Url: string, Html: string, Title: string, Keywords: string, Description: string, InfoTypeId: number, DateCreated: Date, DateUpdated: Date, Hidden: boolean, AMPhtml: string, UseAmp: boolean, UseAmpVideo: boolean, UseCarousel: boolean, TradeOnly: boolean, TagId: number}> = [];
TagIds = [];
getBuyingGuidesNotFiltered() {
this.IsWait = true;
this._SharedService.getAll().subscribe((data: any[]) => {
data.forEach(e => {
if(e.InfoTypeId === 12)
{
this.infos.push(new infoPage(
e.InfoPageId,
e.DepartmentId,
e.Name,
e.Url,
e.Html,
e.Title,
e.Keywords,
e.Description,
e.InfoTypeId,
e.DateCreated,
e.DateUpdated,
e.Hidden,
e.AMPhtml,
e.UseAmp,
e.UseAmpVideo,
e.UseCarousel,
e.TradeOnly,
e.TagId
));
}
})
this.getFiltered(this.infos);
this.IsWait = false;
});
}
getFiltered(infos: Array<infoPage>) {
var filteredResults = []
for(var i = 0; i < this.infos.length; i++) {
for(var j = 0; j < this.TagIds.length; j++) {
if(this.infos[i].TagId === this.TagIds[j]) {
filteredResults.push(this.infos[i]);
}
}
}
this.infos = [];
this.infos = filteredResults;
}
现在的问题是我的对象数组“infos”包含重复数据,例如:
this.infos = [
{InfoPageId: 8, DepartmentId: 1, Name: "Pitched Roof Window Buying Guide", Url: "buying-guide-pitched", TagId: 15"}
{InfoPageId: 8, DepartmentId: 1, Name: "Pitched Roof Window Buying Guide", Url: "buying-guide-pitched", TagId: 12"}
]
但是你可以看到 TagId 是不同的。
我希望能够遍历我的“infos”数组,并且只将对象添加到我的“filteredResults”数组中,但也仅当每个具有相同“InfoPageId”的对象的 TagId 存在于“ Tagids 的阵列。例如,如果“InfoPageId”为 8 的对象的 TagId 为 12 和 15,而“TagIds”数组的值为 12 和 15,则将对象添加到“filteredResults”数组中,但是如果对象仅包含12 但 'TagIds' 数组的值 12 和 15 不相加。
所需输出的示例;
输入:
TagIds = [10, 5]
infos = [
{InfoPageId: 11, DepartmentId: 1, Name: "Flat Roof Window Buying Guide", Url: "buying-guide-rooflights", Tagid: 10"}
{InfoPageId: 11, DepartmentId: 1, Name: "Flat Roof Window Buying Guide", Url: "buying-guide-rooflights", Tagid: 5"}
{InfoPageId: 12, DepartmentId: 1, Name: "Flat Roof Window Buying Guide", Url: "buying-guide-rooflights", Tagid: 10"}
]
输出:
filteredResults = [
{InfoPageId: 11, DepartmentId: 1, Name: "Flat Roof Window Buying Guide", Url: "buying-guide-rooflights", Tagid: 10"}
]
希望你们能理解这一点。它很难解释。
【问题讨论】:
-
你真的应该给出输入和期望输出的例子
-
好吧,我实际上理解了你的问题,但没有时间为此编写代码。一般的想法是像你一样做(可能使用过滤器函数和 indexOf 或包含函数)。之后,我将构建 InfoPageId: [TagID] 的映射,然后过滤掉那些不在所需条件中的映射。之后,您可以轻松地用剩下的任何东西过滤原始数组。希望你得到我的回答
-
更新了您的建议,例如输入/输出
-
通过您发布的示例,我假设您希望过滤后的结果与 所有 TagIds 匹配。是这样吗?
-
是的,这是正确的。我知道如何删除重复项,但不确定如何执行该逻辑
标签: javascript html arrays angular filter