The missing elements or fields are lost when JSON.stringify is used

Here is the code snippet in question:

// retrieving data via ajax
$.ajax({
    'async': false,
    'global': false,
    'url': url,
    'dataType': "json",
    'success': function (d) {
        data = d;

        // code block to define & calculate voteCount

        data.votes.totalVotes = voteCount;
        localStorage.setItem(url, data);
    }
    , 'error': function (msg) {
        throw new Error("Error while fetching data from " + url);
    }
});

If I type data.votes.totalVotes in the console after the above line:

data.votes.totalVotes = voteCount;

I receive the expected value. However, when I try JSON.stringify(data), the property totalVotes does not appear.

Do you have any insight into why this might be happening, or suggestions for how to resolve it?

** Please note: I have ruled out asynchronous issues as the cause, as the problem persists even within the success callback.

Answer №1

Here is the revised code for your $.ajax request:

let retrievedData;
$.ajax({
    'async': false,
    'global': false,
    'url': url,
    'dataType': "json",
    'success': function (data) {
        retrievedData = data;
        retrievedData.votes.totalVotes = voteCount;
        localStorage.setItem("myData", JSON.stringify(retrievedData));
    }, 'error': function (message) {
        throw new Error("Error occurred while fetching data from " + url);
    }
});

Answer №2

Apologies for my confusion earlier. It turns out that votes is actually an array, so my attempt to set totalVotes as a property on the array was causing it to be omitted during serialization.

For anyone else who might make the same mistake, hopefully this clarification can prevent any further confusion.

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

Convert a JSON string into an HTML format

My JSON string (received from the server response) contains HTML tags, for example abc<br/>dd. This string is then placed in a DOM element as its content. Is there a way to render it as actual HTML code instead of just a plain string? ...

Tips for emphasizing the current element without disrupting existing styles

Is there a way to highlight an element with a border without causing it to shift? The script seems a bit glitchy when detecting mouse leaving the area. I'm unable to override parent element properties like border or outline. I also can't use pse ...

angularjs controller cross-validation for forms

I am faced with a dilemma involving two controllers: btnController and formController. Specifically, I need to submit a Form from another controller action while ensuring that the function in the controller is only called when the Form Validation is Valid. ...

What is the best way to dynamically hide a textbox in JSP based on the selection of a

On my JSP page, I have a textbox and a checkbox. I attempted to use jQuery and JavaScript to hide the textbox when the checkbox is checked, but it doesn't seem to be working. Below is the code snippet: <p class="contact"> <input id="check" n ...

Creating personalized columns in a BootstrapVue table

I'm having an issue with the b-table component in bootstrap-vue. The array containing my items is structured like this: [{ id: 1, name: "Test", phone: 555-111-666, address: "Some Address", //etc... }] I have a couple of question ...

I'm facing an issue with converting my object to an array as I keep getting the message: "ERROR TypeError: undefined

ERROR TypeError: undefined is not a function Why am I unable to convert my object to an array? This error keeps popping up as I attempt to map all the items that are currently objects but need to be converted into arrays for mapping. How can I accomplish ...

What are the best methods for preventing scss styles from leaking between pages?

I'm currently working on a project that includes the following files: /* styles/1.scss */ body { /* Some other styles not related to background-color */ } /* styles/2.scss */ body { background-color: blue; } // pages/one.js import "../styles/ ...

Django app with Vue.js integration is throwing a 405 error for Axios PUT request

I have a project in progress for managing inventory on a small scale. One of the functionalities I'm working on involves updating the stock quantity when a product is withdrawn. I've encountered an issue while using Axios and the .put() function, ...

A method for automatically refreshing a webpage once it switches between specific resolutions

On my page www.redpeppermedia.in/tc24_beta/, it functions well at a resolution of over 980px. However, when the resolution is brought down to 768px, the CSS and media queries alter the layout. But upon refreshing the page at 768px, everything corrects itse ...

Switch up a JSON string using JavaScript

I received a JS string through an AJAX API call containing data like this: {"Task":"Hours per Day","Slep":22,"Work":25,"Watch TV":15,"Commute":4,"Eat":7,"Bathroom":17} My goal ...

Is it advisable to hold off until the document.onload event occurs?

I'm working with a basic HTML file where I need to generate SVGs based on data retrieved through an AJAX call. Do I need to ensure the document is fully loaded by enclosing my code within a document.onload = function() { ... } block, or can I assume ...

A guide to utilizing asynchandler within a class in Node.js

I'm currently in the process of converting my routers into a class structure, but I'm facing a challenge when trying to wrap the asyncHandler function inside the class. Can anyone provide guidance on how to achieve this? userController.js const ...

Exploring the basics of Three.js: a step-by-step guide using a shadertoy example on transforming patterns with objects

Check out this snippet, inspired by the second live example found at : html, body { height: 100%; margin: 0; } #c { width: 100%; height: 100%; display: block; } <canvas id="c"></canvas> <script type="module"> // Three.j ...

Serialize the elements within an array using JSON.stringify

I'm trying to convert an object into a string, but for some reason it's not working correctly: function httpRequest(url) { this.url = url; this.headers = []; } var req = new httpRequest("http://test.com"); req.headers["cookie"] = "version=1 ...

Iframe form submissions

I am interested in accomplishing the following task. My objective is to submit a form to my booking engine and show the results on either a new page or within a Div element. Ideally, when the user clicks the submit button, it would display an Iframe or re ...

Adding content in real-time at the current cursor position within a Contenteditable element using Angular

I have a contenteditable div where I am facing an issue with pasting text. Whenever I try to paste some text into the div, it always gets pasted at the end. I am using ViewChild to access the reference of the contenteditable div and utilizing innerText to ...

What is the best way to create a JavaScript animation for altering the width of a div element?

Need help with creating a dynamic poll chart based on YES and NO votes? Check out this project where you can visually see the results by clicking HERE. Looking to add some animation effects to your poll? You can achieve a smooth transition using CSS with ...

Utilizing Jquery tabs for consistent height display

Currently, I am utilizing jquery tabs for showcasing various content. This is what my functions look like: $(function() { $( "#tabs" ).tabs(); }); I attempted to ensure all tabs have the same height by using this approach: var heightStyle = ...

Modifying the Redux state using an array with prototypes

In my React application, I am utilizing Redux along with the ChartJS library to create charts. Occasionally, when I extract an array from the global Redux state, it appears in this format: ejeY: Array(7) 0: 43783 1: 85001 2: 100960 3: 752 ...

Tips for transforming a non-JSON string into a correctly formatted JSON string using PHP

I'm currently working with an API service that connects to a web-based SMS provider. When I make a call to the API, I receive the following response: {Promotional SMS Credits: 0, Transactional SMS Credits: 9972} Although I attempted to use json_deco ...