Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects that contains string using lodash

Tags:

I have a value and i need to return the objects that contains this value in propertie.

var search='CPP@'; var results=_.filter(collection,{VAL:search}); 

I need to grab all objects that constains 'CPP@' , not the equals. I've prepared a https://jsfiddle.net/licass/e87mxfqt/

like image 798
Leonel Matias Domingos Avatar asked Jun 16 '16 13:06

Leonel Matias Domingos


People also ask

Can you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

What does Lodash filter return?

Apr 6, 2020. Given an array arr , Lodash's filter() function returns an array containing all the elements in arr for which the function returned a truthy value. const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; _.filter(arr, isEven); // [2, 4, 6, 8] function isEven(v) { return v % 2 === 0; }


1 Answers

var collection=[    {      "DSP_MAQ": "Máquina 4",      "VAL": "CPP@4@1900-01-01"    },    {      "DSP_MAQ": "Máquina 5",      "VAL": "CMIP@5@1900-01-01"    },    {      "DSP_MAQ": "Máquina 6",      "VAL": "CMIP@6@1900-01-01"    },    {      "DSP_MAQ": "Máquina 7",      "VAL": "CMIP@7@1900-01-01"    },    {      "DSP_MAQ": "Máquina 8",      "VAL": "CPP@8@1900-01-01"    },    {      "DSP_MAQ": "Máquina 9",      "VAL": "CMIP@9@1900-01-01"    },    {      "DSP_MAQ": "Máquina 10",      "VAL": "CMIP@10@1900-01-01"    }     ];   var search='CPP@';      var results=_.filter(collection,function(item){      return item.VAL.indexOf(search)>-1;      });      console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
 var search='CPP@';     var results=_.filter(collection,function(item){     return item.VAL.indexOf(search)>-1;     });     console.log(results); 
like image 192
Vladu Ionut Avatar answered Oct 20 '22 16:10

Vladu Ionut