简体   繁体   中英

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?

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); 

You can do it using the following code, it uses Array.prototype.filter() and String.prototype.match()

 let arr = [ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ "320", "X3", "X5" ] }, { "name":"Fiat", "models":[ "500", "Panda" ] } ] arr = arr.filter(function(val){ return val && val.name && val.name.match(/F/g); }); console.log(arr); 

What you need to do is run a loop through your array and check whether the condition is getting satisfied or not.

Hope this helps.

 var arr=[ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ "320", "X3", "X5" ] }, { "name":"Fiat", "models":[ "500", "Panda" ] } ]; document.addEventListener('DOMContentLoaded',function(){ console.log(arr.length); for(var i=0;i<arr.length;i++){ if(arr[i].name.startsWith("F")){ Object.keys(arr[i]).forEach(function(key){ alert(arr[i][key]); }) } } }) 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM