I have an Array Data
:
var Data = [{"Nombre": "A","Apellido": "B","Edad": 12},{},{},{},...]
How can I filter the data so that it gives me as a result all that have the Apellido
same as B
for example?
I have an Array Data
:
var Data = [{"Nombre": "A","Apellido": "B","Edad": 12},{},{},{},...]
How can I filter the data so that it gives me as a result all that have the Apellido
same as B
for example?
From the following code:
$(Data)
makes the Data variable an object ofjQuery
..filter
is a function ofjQuery
, directly from its official website: http://api.jquery.com/filter/ it says the following:Interpreted into good Spanish:
In this case, we use
function(index, element)
the documentation says:Interpretation into good Spanish:
In this case, each
element
represents a{"Nombre": "AA","Apellido": "B","Edad": 12}
and since we need to obtain that element that has its property (LastName) equal to "B":return element.Apellido==='B';
Now, the filter variable is an array that contains the new set of filtered elements (forgive the redundancy).
A for loop allows us to iterate through all the elements and finally display them using a
console.log
.Hello you can use
Array.filter
it is native JavaScript was added in the ECMAScript5 specification so it is supported by almost all browsers today.For your particular problem it is quite simple, but if you simplify it with the new notation:
I invite you to try also
Array.find
, which is similar but it returns the first element that matches the filter, in case none of them match, it will returnundefined
.Note : Recommendation start using
let
instead ofvar
in order to have more control over the scope of the variables you define. You can read more aboutlet
.There are many ways to filter that Array of objects
data
, for example:The variable
contenidoFiltrado
, contains all the elements of the Arraydata
, whichApellido
starts withB
.