0

I want to store the following into local storage with a structure like so:

{
  "stuff": [
    {
      "user1": {
        "numbers": [
          1,
          2,
          3
        ]
      },
      "user2": {
        "numbers": [
          2
        ]
      }
    }
  ]
}

How would I go about doing this?

2
  • Your structure is invalid. An array doesn't contain key/value-pairs. Could you fix the structure? Commented Jun 18, 2020 at 16:21
  • @3limin4t0r i've updated the question Commented Jun 18, 2020 at 19:54

2 Answers 2

2

This works for me.

    (() => {
  // ok
  const map = new Map();
  map.set(1, {id: 1, name: 'eric'});
  // Map(1) {1 => {…}}
  localStorage.setItem('app', JSON.stringify([...map]));
  // undefined
  const newMap = new Map(JSON.parse(localStorage.getItem('app')));
  // Map(1) {1 => {…}} ✅
})();
Sign up to request clarification or add additional context in comments.

Comments

1

to save

localStorage.setItem("name",JSON.stringify(Map));

to read

JSON.parse(localStorage.getItem("name"));

3 Comments

I have tried just doing JSON.stringify(Map) and it is persisting as {} meaning its showing up as empty for some reason
Your object need to be like [{"userID1": [1, 2, 3]}, {"userID2": [1, 2, 3]}] and if problem is Map then try to change its name
For me too, it is not stringifying the Map object. It is stringinfying as {}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.