简体   繁体   English

通过数组元素的子字符串环回过滤数组中的对象

[英]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. 我希望它按名称元素过滤,并且只返回名称元素中包含“ F”的对象。 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? 我该如何在Loopback角度SDK中执行此操作?

You can combine the methods Array.prototype.filter() and String.prototype.includes() : 您可以结合使用Array.prototype.filter()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() 您可以使用以下代码进行操作,它使用Array.prototype.filter()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]); }) } } }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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