gpt4 book ai didi

javascript - js中如何过滤对象数组?

转载 作者:行者123 更新时间:2023-12-01 02:40:15 25 4
gpt4 key购买 nike

我正在尝试在我的 Angular 4 组件中过滤我的数组。该数组有一个属性,它本身也是一个数组:

export const data = [
{
"number": "1",
"lines": [
"aaaaabbbb bbbbb ccccc ddddd",
"aaaaabbbb bbbbb ccccc ddddd",
"aaaaabbbb bbbbb ccccc ddddd",

]
}
,
{
"number": "2",
"lines": [
"aaaaabbbb bbbbb ccccc ddddd",
"aaaaabbbb bbbbb ccccc ddddd",
"aaaaabbbb bbbbb ccccc ddddd",

]
}
,
{
"number": "3",
"lines": [
"aaaaabbbb bbbbb ccccc ddddd",
"aaaaabbbb bbbbb ccccc ddddd",
"aaaaabbbb bbbbb ccccc ddddd",
]
}
]

这是 component.html 的一部分:

<input (keyup)="search($event.target.value)" />
<tr *ngFor="let item of filteredData">
<td>{{item.number}}</td>
<td>{{item.lines}}</td>
</tr>

这是过滤器/搜索 ts 代码的一部分:

export class AppComponent {
filteredData = data;

search(val: any) {
let ind = false;
console.log(val);
if (!val) this.filteredData = this.data;
//this statement does not work:
this.filteredData = this.data.filter(item=> item.lines.indexOf(val) >=0)
}
}

如何过滤我的数据?忽略 Angular 代码,更多的是关于过滤器语句。

最佳答案

类似这样的事情

this.filteredData = this.data.filter((item) => {
return item.lines.filter((inner) => {
return inner.includes(val);
}).length > 0;
});

或者

for (const item of this.data) {
for (const inner of item.lines) {
if (inner.includes(val)) {
return item;
}
}
}

关于javascript - js中如何过滤对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com