I have this example JSON containing 2 elements:
[
{
"Fecha":"2018-05-08T00:00:00",
"Proyectado":0,
"Requerido":0,
"Faltante":0,
"stock_resultado":0,
"IdProducto":"88C9B788-2009-47B3-5690-532E2CF84E56",
"Consecutivo":184
},
{
"__KEY__":"4a558959-bb63-68a2-2e87-358d678c6ec8",
"Fecha":"2018/06/16 00:00:00",
"Proyectado":2,
"CantidadProyeccion":"8",
"IdProducto":"7723EE8E-824C-7D19-1205-4B175D4A5DCB"
}
]
From the above JSON I need to filter those elements whose IdProducto
is 88C9B788-2009-47B3-5690-532E2CF84E56
.
I've tried using the " filter
" function, but it always returns the same amount of data "for this case, there are (2) elements in the object" .
Example of what I'm trying to do 1 :
var arreglo_muestra = [{
"Fecha": "2018-05-08T00:00:00",
"Proyectado": 0,
"Requerido": 0,
"Faltante": 0,
"stock_resultado": 0,
"IdProducto": "88C9B788-2009-47B3-5690-532E2CF84E56",
"Consecutivo": 184
}, {
"__KEY__": "4a558959-bb63-68a2-2e87-358d678c6ec8",
"Fecha": "2018/06/16 00:00:00",
"Proyectado": 2,
"CantidadProyeccion": "8",
"IdProducto": "7723EE8E-824C-7D19-1205-4B175D4A5DCB"
}];
function obtenerProductoPorId(IdProducto) {
return IdProducto = "88C9B788-2009-47B3-5690-532E2CF84E56";
}
function myFunction() {
document.getElementById("demo").innerHTML = JSON.stringify(arreglo_muestra.filter(obtenerProductoPorId));
}
<p>Presione el botón para obtener el objeto filtrado por IdProducto:</p>
<button onclick="myFunction()">Filtrar producto por ID</button>
<p id="demo"></p>
I really don't know why it doesn't work as I suppose it should.
How can I filter this sample object using .filter()
or other javascript functionality?
1 Code adapted from this page .
As the documentation says , you must receive an element and within it the condition that must be fulfilled, keep in mind that it will return another array of objects, it can be with zero elements or several
Mauricio, I propose this function:
It will receive in parameter the array, the key and the value that you want to filter and it will return the result.
I think that this way the code could be more portable.
I have applied a practice that seems recommendable to me: free the DOM elements from any function, relegating it to a listener by its id, in this way, the DOM elements are more independent.
Using the arrow function, the solution is a little shorter, in this solution we apply the function
filter
to the variablearray
, passing as a parameter each object represented ase
then the function willfilter
traverse each object within the array, filtering thatIdProducto
of each traversed element and returning the result as to the condition.here the documentation