get specific element of object in local storage
I'm saving an object in local storage, and the I want to list all the items when I load the page again, but I don't know how to get the info from the object elements. Any ideas? Here's my code:
var estudiantes = [];
function agregaArray(i) {
estudiantes.push({
"carnet": $("#carnet_" + i).text(),
"apellidos": $("#apellidos_" + i).text(),
"nombre": $("#nombre_" + i).text(),
"e1": $("#examen1_" + i).val(),
"e2": $("#examen2_" + i).val(),
"e3": $("#examen3_" + i).val(),
"prom": $("#promedio_" + i).text()
});
}
function agregaLocalStorage() {
localStorage.setItem("114270311_estudiantes", JSON.stringify(estudiantes));
}
$("#list").click(function () {
for (var i = 0; i < localStorage.length; i++) {
var obj = JSON.parse(localStorage.getItem(localStorage.key(i)));
console.log(obj.carnet);
console.log(obj.apellidos);
console.log(obj.nombre);
}
});
Those console.logs return an "undefined" and I want to get the specific info.
Thanks for the help.
Answers 1
From your code not able to find out how you are calling
agregaArray()
&agregaLocalStorage()
; function. You can dolocalStorage.setItem..
insideagregaArray
function and avoid a second function.Also doing
localStorage.length
will return all the stored items which may not be your interest.Instead you need only item stored by this key114270311_estudiantes
.For demo I am hard coding the values for the json.
Hope this snippet will be useful
Working jsFiddle