Storing Arrays with String Keys in LocalStorage using JavaScript

When attempting to save an array in localStorage, the values associated with String keys seem to disappear.

Here's an example:

var myArray = [];

myArray["key1"] = "value1";
myArray[123] = "value2";

Initially, everything seems to work fine and the expected output is attained:

myArray["key1"] => value1
myArray[123] => value2

However, when trying to store the array using this method:

localStorage.setItem('myStoredArray',JSON.stringify(myArray));
var myArray = JSON.parse(localStorage.getItem('myStoredArray'));

The result no longer includes the value linked to a String Key:

myArray["key1"] => undefined
myArray[123] => value2

Is there something incorrect in my approach? Should this be working as expected, or is there another way to save the array while retaining the values connected to String keys?

Any assistance would be greatly appreciated!

Answer №1

JavaScript does not have associative arrays. Instead, it uses objects where all keys are automatically converted to strings.

var newObj = {}; // <<< update made here

newObj["key1"] = "value1";
newObj[123] = "value2";

Answer №2

According to the comments from Daniel, the issue with your array lies not only in its persistence but also in its creation process.

This can be easily observed in your browser's console:

>var myArray = [];
<undefined
>myArray["key1"] = "value1";
<"value1"
>myArray
<[]

It is clear that trying to assign a value to an array using a String key does not function as expected.

Consider utilizing ES6 Maps or an object instead.

While Daniel has already provided the Object method, here is how you can use a Map:

var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("123", "value2");

An advantage of using a Map is the simpler iteration process:

for (var [key, value] of myMap.entries()) {
  console.log(key + " = " + value);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to retrieve data from a MongoDB database in JSON format via an API call? If you're working with JavaScript, Node.js, Express, and MongoDB, we can help you

Below is how I establish the connection to the database: > // Connecting MongoDB using MongoClient > > const MongoClient = require('mongodb').MongoClient > > const url = 'url is used' > > const dbName = 'vir ...

Guide to displaying personalized metadata on the front end using WP Store Locator

I would like to insert a unique text into the information windows located beneath the Store details (below Email). https://i.sstatic.net/2ItMW.jpg Following the guidelines from: To implement this feature, I made the necessary adjustments in the function ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

Stack the labels of separate datasets on top of each bar in a bar chart using Chartjs: How can this be achieved?

chart.js 4.4.2 chartjs-plugin-datalabels I am aiming to achieve this effect const chartCtr = document.querySelector('#temp-chart1') as HTMLCanvasElement; new Chart(chartCtr, { type: 'line', plugins: [ChartDataLabels], opt ...

What is the method for comparing a value in TypeScript that does not match a given value?

I am new to scripting languages and encountered an issue while using enums with if-else statements in TypeScript. To work around this problem, I have decided to use switch-case instead of if-else conditions. Despite trying !== and !===, they do not seem t ...

Creating Combinations Through Distributing Array Elements according to a Common Condition in PHP

I'm working with a complex multidimensional array that has a unique structure: array( array(["AF2021A"], ["AF2021B"], ["AF2020C"]), array(["IR2022A","IR2021A"], ["IR2022B","IR20 ...

How can I show information in a Rich Textarea when an AJAX request is successful using JavaScript?

Below is the code snippet: <textarea class="textarea" id="about_us" placeholder="Place some text here" style="width: 100%; height: 100%; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px; ...

Why should one bother with specifying types when defining a variable in Typescript?

As someone new to Typescript, I've come to appreciate its many advantages when working on larger applications and with multiple team members :) Imagine you have the following TypeScript code: declare const num = 5: number; Why is this better than: ...

Header reference differs from the document referrer

this is the request header: GET / HTTP/1.1 Host: localhost:3002 Connection: keep-alive sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" sec-ch-ua-mobile: ?0 User-Agent: ...

Preserve changing data with angular

Can you advise on integrating an array created in a form's value with Laravel for database storage? I am dynamically generating inputs and checkboxes within the component. The component features one input field and three checkboxes: public s ...

Assigning Values from Multidimensional Arrays to Class Properties

Utilizing PDO for querying a MySQL database and retrieving an array of bikes categorized by their model type. The array returned comprises various attributes like part number, color, size, etc., indexed by numeric keys. An exemplar structure is as follows: ...

React - Dealing with rendering issue when toggling a button using LocalStorage and State

For quite some time now, I've been struggling with a particular issue... I'm encountering challenges in using the current state to display a toggle button that can both add and remove an item from local storage. The code below manages to add and ...

Map checkboxes aren't updating after an array update following a refactor to react hooks

I recently transformed a class component into a function component using hooks. However, I am facing an issue where the checkboxes within a specific mapping are not updating with the checked value. The onChange handler is firing and updating the array corr ...

Trying out a template component with a dynamic function for disabling

Here's an interesting scenario I encountered: A template disables a certain element based on the input of another element. <input id="email" type="text" [(ngModel)]="login.username" name="username" <button type="button" id="login-button" [disab ...

How can circular dependencies be resolved within Angular dependency injection?

Is there a solution to resolving circular dependency injection errors in Angular 1.x? I'm aware of using the injector to inject a service. However, are there other alternatives to address this issue? Furthermore, is it acceptable to implement this ...

Preventing Users from Accessing a PHP Page: Best Practices

I'm currently focusing on a problem that involves restricting a user from opening a PHP page. The following is my JavaScript code: <script> $('input[id=f1email1]').on('blur', function(){ var k = $('inp ...

Converting a multidimensional array into an object with a unique method

Although this question has been asked multiple times before, I am still struggling to achieve the desired outcome. Essentially, I have an array that looks like this: array(7) { ["site"]=> array(5) { ["production"]=> bool(false) ["ur ...

Is my Magento journey on the correct course?

I am wanting to include or require a file in DATA.php within magento. Below is the code snippet I have: public function formatPrice($price) { require_once(Mage::getBaseDir('app').'\design\frontend\neighborhood ...

React - passing down a ref as a prop isn't functioning as expected

In my current project, I am utilizing the react-mui library and aiming to incorporate a MenuList component from the MenuList composition available here. An issue arises when passing a ref as a prop down to a child component containing a menu. For reference ...

Utilizing commas in JavaScript

Hi everyone, I'm having an issue with printing the message "Invalid password, Must Contain:". The problem I'm facing is that when I write the code in JavaScript, the comma is being interpreted as an operator instead of a regular English comma. Th ...