Diesan Romero
Diesan Romero

Reputation: 1658

Problem with for loop and localstorage in javascript

I have this code and it is functional, but the only problem is that it does not save me the localstorage as I really want. The loop keeps all the keys but with the same last value:

"use strict";

var form = document.querySelector("#form");

form.addEventListener("submit", function() {
  var name = document.querySelector("#name").value;
  var year = document.querySelector("#year").value;
  var productor = document.querySelector("#productor").value;
  var director = document.querySelector("#director").value;

  if (name === "" || year == "" || productor == "" || director == "") {
  } else {
    let body = document.querySelector("tbody");
    var tr = document.createElement("tr");
    body.appendChild(tr);

    var datos = [name, year, productor, director];
    var keys = ["name", "year", "productor", "director"];
    for (var k in keys) {
      for (var d in datos) {
        localStorage.setItem(keys[k], datos[d]);
      }
    }


    for (let d in datos) {
      var td = document.createElement("td");
      tr.appendChild(td);
      var text = document.createTextNode(datos[d]);
      td.appendChild(text);
    }
  }
});

var clear = document.querySelector("#clear");

the problem I suppose is right here:

for (var k in keys) {
      for (var d in datos) {
        localStorage.setItem(keys[k], datos[d]);
      }
    }

Upvotes: 1

Views: 61

Answers (1)

benvc
benvc

Reputation: 15120

As noted in my comment, you are overwriting the value of each key with each iteration of your inner loop (and setting them all to the last value in your datos array). I think you are looking to set each key in your keys array to a value corresponding to the item at the same index in your datos array. For example:

const datos = ['Working Title', '2018', 'Patty Producer', 'Danny  Director'];
const keys = ['name', 'year', 'productor', 'director'];
keys.forEach((k, i) => {
  localStorage.setItem(k, datos[i]);
});
    
console.log(localStorage.getItem('name')); // Working Title

Upvotes: 1

Related Questions