items disappearing

In my Angular application, I am attempting to save and retrieve data between pages using the following function:

$scope.storeData = function () {

    var selections = $scope.devices;
    console.log(selections);

    sessionStorage.setItem('selectedHandsets', JSON.stringify(selections));

    var ss = sessionStorage.getItem('selectedHandsets');
    console.log(ss);

}

However, I have encountered a strange issue. The values 'selectedManufacturer' and 'selectedModel' that I need from selections are visible in the console log output of console.log(selections).

Yet, when I check the contents of ss (retrieved from sessionStorage.selectedHandsets), those keys are mysteriously missing. Even though they were present during the setting of the data into selections, they vanish when logging ss!

The structure of selections is as follows:

[
    [
        { ... },
        { ... },
        selectedModel: { ... },
        selectedManufacturer: { ... }
    ],
    [
        { ... },
        { ... },
        selectedModel: { ... },
        selectedManufacturer: { ... }
    ]
]

If I wrap JSON.stringify() around console.log(selections), the selectedModel and selectedManufacturer disappear. Can anyone explain why this is happening and suggest an appropriate solution?

Answer №1

Have you checked the console for any error messages?

It appears that the JSON data is not formatted correctly

[
    [
        { ... },
        { ... },
        selectedModel: { ... },
        selectedManufacuterer: { ... }
    ],
    [
        { ... },
        { ... },
        selectedModel: { ... },
        selectedManufacuterer: { ... }
    ]
]

Please pay attention to

    [
        { ... },
        { ... },
        selectedModel: { ... }, //There shouldn't be a named item in an array here
        selectedManufacuterer: { ... } //There shouldn't be a named item in an array here
    ]

Avoid using named objects within an array.


Corrections have been made:

Your initial approach was similar to this:

var arrayBuff= [];
arrayBuff.push(2);
arrayBuff.push(4);
arrayBuff.push(6);

//this would result in: [2, 4, 6]
console.log(arrayBuff);

arrayBuff.someField = "foobar";

//this would result in: [2, 4, 6, someField: "foobar"]
// which is not a valid array format
console.log(arrayBuff);

Try this instead:

var arrayBuff = {},
    arrayBuff.arrays = [];
arrayBuff.arrays.push(2);
arrayBuff.arrays.push(4);
arrayBuff.arrays.push(6);

//this would result in: { arrays: [2, 4, 6] }
console.log(arrayBuff);

arrayBuff.someField = "foobar";

//this would result in: { arrays: [2, 4, 6], someField: "foobar"}
// this format can be parsed correctly by JSON.stringify
console.log(arrayBuff);

The issue with parsing the named field using JSON.stringify was because it expected an array, not a named object.

Answer №2

Yes, the correct approach is to organize your selections into an object structure such as { arrayObjects : [ place your array here], models: [...], brands:[...] }

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

Warning in React: You cannot use functions as a child element

My React component is causing issues with rendering and giving me a persistent warning The error message reads: "Functions are not valid as a React child. This may happen if you return a Component instead of from the render function. Or maybe you meant t ...

Transitioning from left to right, picture smoothly scrolls into view using Way

I've explored various websites and even attempted to decipher a waypoint guide, but unfortunately, I haven't had any success. The scroll function doesn't seem to be working with the code below. (source: ) Any assistance on this matter would ...

Is there a way to prevent repeating the same value in a consecutive subsection of an array without using a loop?

I am working on a program that involves repeating a series of methods to simulate time evolution. As part of this process, I need to set the same value for a large subset of elements in a very large array. Instead of using a loop to manually assign these v ...

Ways to retrieve the selected option from a dropdown list

How can I extract the option value from a dynamically populated Select button in order to retrieve the necessary data from my database? I am unsure of how to obtain the value stored in the $giftName variable. I have attempted to use both jQuery and JavaS ...

Modifying dynamic input fields based on the selected input field type

Seeking advice on a challenge I'm facing while testing a website. My task is to mask input fields in screenshots after executing tests because we share data with other teams. I've tried using JS before the script by changing the input type to &ap ...

The ng-include directive is having trouble finding the partial HTML files

I've been working on setting up a basic tabset with each tab pulling content from a separate partial view with its own controller. To test everything out, I created three dummy HTML files with simple text only. However, I'm having trouble getting ...

What is the best way to check the validity of a recursive function in Z3 that takes an array selection as an argument in an SMT specification

My current research focuses on automatic program verification using Z3 as an SMT solver. Specifically, I am working on parsing annotated programs that contain specifications of their intended behavior to automatically generate and verify proof obligations ...

Using a pre-existing HTML template in an Angular project

Looking at my html template file named range-details-dialog.tpl.html <div class="modal-header clearfix text-left"> <h5>Update Range</h5> </div> <div class="modal-body"> <form name="form" ...

simpleCart - Utilizing a modal window for easy input and sending the shopping cart data to PHP in a multidimensional array

Currently, I am working with the simpleCart JavaScript shopping cart, but I have encountered a minor issue. When a customer clicks "checkout," a modal pops up requiring them to enter their contact information. Upon submitting the form, an email is sent to ...

Is there a way to retrieve the BrowserRouter history from outside of the BrowserRouter component?

Here is a simplified code snippet (using react-router-v5). I am trying to figure out how to access BrowserRouter's history in the logout_Handler() function, even though I am "outside" BrowserRouter. I came across this answer on How to access history ...

What is the best way to perform a single asynchronous or promise-based fetch request and utilize the retrieved data across multiple functions?

Is there a way to optimize fetching data from an API and use the fetched data in multiple methods within the same service without making redundant requests in the Network? export class MediaService { constructor(private mediaAppApiService: MediaAppApiS ...

Bot is being inundated with messages containing no content

My discord.js version is 14.0.3. I'm facing an issue where the message content is not being retrieved correctly. To solve this, I set up a client.on('messageCreate') event handler: client.on('messageCreate', async (message) => ...

Leverage JavaScript libraries utilizing namespaces within your Angular application

I have a unique JavaScript library that includes functions organized within namespaces. For example: var testNamespace = { insideFunction: function(str) { alert(atr); } }; Now, I am trying to integrate these functions into my Angular app.c ...

Challenges of modifying a scope object in Angular through reference

I am encountering a challenge when trying to update a reference of an object within my code. Here's the scenario: function modifyUserDetails(user) { $scope.initialUser = user; $scope.alteredUser = angular.copy(user); } ...

Transforming the elements within an expansive Canvas into a high-quality JPEG image

Is there a way to convert the contents of a large Canvas to JPEG format? I need to convert a large canvas, possibly around 1000x1000 pixels or larger, into JPEG format for uploading onto a server. If the canvas was smaller in size, I could have used canva ...

Problem encountered when trying to use a single button for both opening and closing functionality in JQuery

Hello everyone, I'm currently working on creating a button that toggles between opening and closing. When clicked the first time, it should open, and when clicked the second time, it should close and reset. Here is the code I've written so far. ...

What is the best way to access the text content of a nested HTML element for automation tasks with Selenium or Protractor?

Can anyone help me with this HTML code snippet? I want to extract and display only the text within the desc class - "Print this", ignoring the text in the spell class. This needs to be done using either Protractor or Selenium. <span class="desc"> Pr ...

Steps for updating a specific item within an object in an array of MongoDB document

Consider the following data collection, for which I have some questions: { "_id" : ObjectId("4faaba123412d654fe83hg876"), "user_id" : 123456, "total" : 100, "items" : [ { ...

Null value added to MySQL database using Node.js

app.post('/addBeer', (req, res) => { pool.getConnection((err, connection) => { if (err) throw err console.log('connected as id' + connection.threadID) const params = req.body var name = params.n ...

Is the syntax incorrect or is there another reason for the empty array being passed, as the "resolve" callback is running before the completion of the for loop?

The for loop will iterate over the length of req.body, executing a Customer.find operation in each iteration. The resolve function will then be called with an array containing the results of all the find operations. let promise = new Promise(function(res ...