Ani Ani - 2 years ago 149
AngularJS Question

Loopback filter objects in an array by substring of its element

I have an array of objects. I want to filter it in such a way that it only returns the objects which element value matches a particular filter. Like if the element value contains some string, that object will be there in the returning array.

For example if I have an array like this:

[
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]


I want it to filter by the name element and only return the object containing "F" in the name element. Like it'll return only the following

[
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]


how do I do that in loopback angular sdk?

Answer Source

You can combine the methods Array.prototype.filter() and String.prototype.includes():

const data = [{"name": "Ford","models": ["Fiesta", "Focus", "Mustang"]},{"name": "BMW","models": ["320", "X3", "X5"]},{"name": "Fiat","models": ["500", "Panda"]}];
const filterByStr = 'F';
const result = data.filter(obj => obj.name.includes(filterByStr));

console.log(result);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download