Katie Reynolds
Katie Reynolds

Reputation: 337

JavaScript: Trouble with Arrays in localStorage (using JSON Parse)

New to JS. I am trying to store an array in localStorage by converting it to a string using JSON, and then parsing back into an array when I retrieve it from another page on my site. However, I'm not seeing what I expect in the console log after parsing back into an array.

I have not worked with JSON before, so maybe I am doing something wrong. I couldn't find that there was anything I needed to import on my script page to use JSON, but please let me know if I'm missing something.

Example code:

Page 1 HTML:

<div class="test">Some text.</div>
<div class="test">Some text.</div>
<div class="test">Some text.</div>

Page 1 JS:

var allDivs = document.querySelectorAll(".test");
console.log(allDivs);
  // Console Log Output: NodeList(3) [div.test, div.test, div.test]
localStorage.setItem("content", JSON.stringify(allDivs));

Page 2 JS:

var originalArray = JSON.parse(localStorage.getItem("content"));
console.log(originalArray);
  // Console Log Output: {0: {…}, 1: {…}, 2: {…}}

I was hoping that after retrieving on Page 2, the console log would bring back what I saw when I console-logged my original array on Page 1 (NodeList(3) [div.test, div.test, div.test]). Instead, I see that it is converting into some key-value pairs instead of the original array.

How can I return the original array on Page 2? I would like to be able to set up a function that loops through that array on Page 2, without having to manually copy all of the content on Page 1 to a hidden container on Page 2, as the Page 1 content changes daily.

If there is a better way overall that I should approach this, please let me know! I tried a few other things like fetch(url) and jQuery $.load as well, but was having trouble understanding how to make those options work with my code.

Upvotes: 0

Views: 322

Answers (1)

user15672038
user15672038

Reputation:

Nodelist is a collection of nodes which are objects with many properties: https://developer.mozilla.org/en-US/docs/Web/API/NodeList what you could do is:

const result = [];
for (const div of allDivs) {
    result.push(div.innerHTML);
    localStorage.setItem("content", JSON.stringify(result));
}

or alternatively:

const result = Array.from(allDivs).map((div) => div.innerHTML);
localStorage.setItem("content", JSON.stringify(result));

Upvotes: 1

Related Questions