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 do localStorage.setItem.. inside agregaArray 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 key 114270311_estudiantes.

    For demo I am hard coding the values for the json.

    Hope this snippet will be useful

    var estudiantes = [];
    
    function agregaArray() {
        estudiantes.push({
            "carnet": "1",
            "apellidos":"2",
            "nombre":"3",
            "e1":"4",
            "e2":"5",
            "e3": "6",
            "prom":"6"
        });
    }
    function agregaLocalStorage() {
         localStorage.setItem("114270311_estudiantes",JSON.stringify( estudiantes));
    }
    agregaArray();
    agregaLocalStorage();
    
     $("#list").click(function () {
      var m = JSON.parse(localStorage.getItem("114270311_estudiantes"));
       m.forEach(function(key){
         console.log(key.carnet);
         console.log(key.nombre);
         console.log(key.apellidos);
       })
    });
    

    Working jsFiddle


Related Articles