I have an array of objects that fills randomly
var lproducts = [
{
"nombre":"Agua",
"descripcion":"Agua purificada",
"precio": 10.5
},
{
"nombre":"leche",
"descripcion":"leche entera",
"precio": 20
},
{
"nombre":"Manzana",
"descripcion":"Manzana Roja",
"precio": 5
},
{
"nombre":"Galletas",
"descripcion":"Galletas Chocolate",
"precio": 10
}
]
I don't know when an object is added to the array, so I don't know its index, and I want to remove the object whose name property is "Apple". I know that with lproducts.splice(2, 1)
I can remove an object from the array, where the number 2 is the index of the item I want to remove.
What I need to know is the index of the object named apple so I can remove it.
You can create a map of the array where you only get product names, with that you can use
indexOf
You can use the reduce() function of the Array class.
It starts by receiving the first element in
anterior
, the second in ,actual
and the index of the current one inindice
. It goes through the entire array like this and if the value of any matches, it returns its index.filter()
I would use the or methodfind()
. Here's a test search function:To this function you pass your array ( lproducts ) and the searched name ( Apple ) as a parameter.
The filter() method returns an array with all the elements that pass the test. In this case, it returns the products whose key name is equal to the name that we pass to the function.
NOTE: The difference between the find() and filter() methods is that (if there are results) find() returns the first result found and filter() returns an array with all the results. If in your case, name is a key that cannot be repeated, you can change filter() to find() .
NOTE2: If what you need is the index, you can use another method by calling findIndex() , similar to find() , but it returns the index instead of the element.
NOTE3: https://stackoverflow.com/questions/19253753/javascript-find-json-value