[英]How to extract elements from an array of objects that contains a subtring - Javascript and Angular 5
I am trying to take the elements on an array that contains a substring. 我试图将包含子字符串的数组上的元素。 For example:
例如:
myArray = [{name: "Pablo Ramon", lastName: "Garcia"}, {name: "Ernesto", lastName: "Salgado"}]
And giving a string to look for str = "Ra"
, I would like to create a new array only with {name: "Pablo Ramon", lastName: "Garcia"}
after applying the filter. 并给出一个字符串以查找
str = "Ra"
,我想在应用过滤器后仅使用{name: "Pablo Ramon", lastName: "Garcia"}
创建一个新数组。
If I am not wrong this is possible using a map
but I do not know how to do it. 如果我没记错,可以使用
map
但我不知道该怎么做。
EDIT 编辑
My current structure is: Object 我当前的结构是: 对象
export class Car{
$key: string;
title: string;
description: string;
}
From the service 从服务
betList: any;
The error that I get after using the next command is: 使用下一条命令后出现的错误是:
Command 1 命令1
this.betList = this.betList.filter(o =>
Object.values(o).some(s => s.includes(title))
);
Command 2 命令2
this.betList = this.betList.filter(o =>
Object.values(o).some(s => s.indexOf(title) >= 0)
);
Error 错误
Property 'includes' does not exist on type '{}
You can filter array using .filter()
and String's .includes()
methods: 您可以使用
.filter()
和String的.includes()
方法来过滤数组:
let data = [{name: "Pablo Ramon", lastName: "Garcia"}, {name: "Ernesto", lastName: "Salgado"}]; let str = 'Ra'; let result = data.filter(o => Object.values(o).some(s => s.includes(str))); console.log(result);
Use a .filter()
in simple way: 使用简单的
.filter()
方法:
var data = [{ name: "Pablo Ramon", lastName: "Garcia" }, { name: "Ernesto", lastName: "Salgado" }]; var result = data.filter(o => Object.values(o).some(s => s.includes("Ra"))); console.log(result);
Another solution without .includes()
: 没有
.includes()
另一种解决方案:
var data = [{ name: "Pablo Ramon", lastName: "Garcia" }, { name: "Ernesto", lastName: "Salgado" }]; var result = data.filter(o => Object.values(o).some(s => s.indexOf("Ra") >= 0 )); console.log(result);
[{name: "Pablo Ramon", lastName: "Garcia"}, {name: "Ernesto", lastName: "Salgado"}]
.filter (p => p.name.includes ('Ra'))
//{name: "Pablo Ramon", lastName: "Garcia"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.