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.
If I am not wrong this is possible using a map
but I do not know how to do it.
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
this.betList = this.betList.filter(o =>
Object.values(o).some(s => s.includes(title))
);
Command 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:
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:
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()
:
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"}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.