I am creating a list of products but what I need later is only to access a part of that list of products that I have made with javascript in this case I only want the product id I am doing it as follows:
function listarProductos(){
var listaProductos = [];
var descripcion = $('.agregarProducto');
var cantidad = $('.nuevaCantidadProducto');
var precio = $('.nuevoPrecioProducto');
for(var i = 0; i < descripcion.length; i++){
listaProductos.push({"id":$(descripcion[i]).attr("idProducto"),
"descripcion":$(descripcion[i]).val(),
"cantidad":$(cantidad[i]).val(),
"stock":$(cantidad[i]).attr("nuevostock"),
"precio":$(precio[i]).attr("precioReal"),
"total":$(precio[i]).val()})
}
$("#listaProductos").val(JSON.stringify(listaProductos));
console.log(listaProductos[id]);
}
As you will see, at the end I try to do something console.log(listaProductos[id]);
so that in the console it only gives me the id of that list, but I think that it is not a correct way to do it.
listaProductos
is an array, it must be accessed using numeric indices:Once you access an element in a position you must see what properties are accessible to this element, as in your case you are accessing an object you have two ways to access its properties:
First form:
Second way:
Note how the second form requires the
"
or'
(single or double) quotes to access the property, you can't access it with a variable unless the variable is strictly astring
, like so;third form