Is there a way to have json.stringify continuously update itself in a loop?

I am experiencing an issue with json.stringify. I have a button on-click event that triggers a function to add another object to the array variable.

var example = [{name: "K", age: 12},{name: "L", age: 12}];
var jsonE = JSON.stringify(example);

Despite adding more objects to the 'example' variable, the value of jsonE remains unchanged.

I am looking for a way to continuously update the json data as new objects are added to the array. Is there a specific loop or method I should be using?

SOLUTION:

Update the JSON.stringify when the on-click event is triggered.

Answer №1

To retrieve objects from JSON format, you can use JSON.parse and then add new objects to it before converting it back to a string.

var example = [{name: "K", age: 12},{name: "L", age: 12}];
var jsonE = JSON.stringify(example);
// Retrieve objects
var exampleParsed = JSON.parse(jsonE);
// Add a new object
exampleParsed.push({name: "M", age: 13});
// Convert the updated array back to a string
JSON.stringify(exampleParsed);

// Output
"[{"name":"K","age":12},{"name":"L","age":12},{"name":"M","age":13}]"

Give this a try and see if it meets your needs (y).

Answer №2

One effective method to separate the array from operations that rely on it is by conceptualizing the array as an observable entity

Here's how you can achieve this: encapsulate the array as an observable and then establish a callback for JSON.stringify dependency.

function ObservableArray() {
   var self = this;
   this.onPushCbs = [];
   this.array = []
   this.push = function(value) {
     this.array.push(value)
     this.onPushCbs.forEach(function(cb) {
        cb(self.array);
     })
   }
}

var arr = new ObservableArray()
// ObservableArray {onPushCbs: Array[0], array: Array[0]}
// Register an event so that every time the array is pushed, the value will
// be logged
arr.onPushCbs = [function(a) { console.log(a)}]
arr.push('1')
// Logs ['1']

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

Converting MongoDB Queries to MySQL in Node: A Step-by-Step Guide

I am currently facing a challenge where I need to migrate my app's database from mongoDB to mysql. The application was initially developed using node.js, but I encountered an issue with the "Create table" query while attempting the conversion process. ...

The Azure website is encountering an issue due to the absence of the specified Node version in the

Within my Azure setup, I am currently using an 'Azure Website' instance to run Docpad (a NodeJS App). In my package.json file, I have specified the following... "engines": { "node": "0.10.21", "npm": "1.x" }, I have tried various entries ra ...

Storing JSON arrays in MongoDB becomes chaotic when using the .save() function from Mongoose

I'm faced with the challenge of storing a lengthy JSON array in a free MongoDB database collection. To achieve this, I establish a connection to my database using mongoose and then utilize a for loop to iterate through each JSON object in the array. ...

Interconnected Dropdown Menus

I've implemented the cascading dropdown jQuery plugin available at https://github.com/dnasir/jquery-cascading-dropdown. In my setup, I have two dropdowns named 'Client' and 'Site'. The goal is to dynamically reduce the list of si ...

Tips for handling the data sent to an API

Before continuing: This question is NOT about accessing a REST API. I am NOT inquiring about how to interact with the endpoint, sending data to it, and parsing the JSON received. Instead, my inquiry pertains to setting up that endpoint in vbScript. I am s ...

What causes the non-reachable part of the ternary operator to be evaluated prior to updating the state with setTimeout?

Check out my latest code snippet for a react component that renders a massive component. While the huge component is still rendering, a loading indicator will be displayed. import * as React from "react"; import ReactDOM from "react-dom"; import {HUGECom ...

Is it possible for a JavaScript .execute function to be executed synchronously, or can it be transformed into an Ajax

Currently, I am utilizing the ArcGIS API for Javascript which can be found at this URL: The JavaScript code snippet I'm working with appears to be running asynchronously. Is there a way to convert it to run synchronously or potentially transform it i ...

Examples for Foursquare using asp.net

As someone who is new to JSON, I find myself a bit puzzled. My goal is to utilize userless access for the foursquare api in order to retrieve venue information for a specific location. Can you provide me with a comparable example using .net? ...

Updating Cart Array in Angular 4 when Adding a New Item

I'm currently using angular 4 and I have encountered an issue in the code where adding a new product to the cart overwrites the existing item instead of appending it to the array. Here is a screenshot illustrating the problem cart.service.ts export ...

Can Vuejs delay the calculation of a computed property until the component is "ready"?

Within my Vue.js application, I have a `computed` property that relies on a value fetched from an AJAX call. I am looking for a way to delay the calculation of this `computed` property until after the `ready` method has completed. While everything is fun ...

Creating a Simple Single Page Application with Node.js and Express

I am currently facing a challenge in getting my tiny SPA app to function properly. Within my app folder, the structure looks like this: /about.html /index.html /index.js index.js: const express = require('express'); const app = express(); co ...

"Changing a Java script base addon file to a customized addon in Odoo 16: A step-by-step guide

Here is the JavaScript file located in the "documents" enterprise base addon: I want to include the field "document_type_id" in the export const inspectorFields = [] array through a custom addon. /** @odoo-module **/ import { device } from "web.confi ...

Are you curious about the array of elements in React's carousel?

I'm currently in the process of constructing a website using React, and I have a specific challenge related to the "news" section. Within this section, I have a list of three components that represent different news items. These components are housed ...

Using dialogue boxes instead of alert and prompt functions in jQuery can enhance user interaction and

I need assistance with implementing a dialog feature in fullcalendar. Currently, I am only able to trigger an alert or prompt when clicking on an event. What is the appropriate JavaScript code to display a dialog? Here is my jQuery code: $(document).read ...

Setting up a Web application testing environment on its own

Embarking on my journey in web application development and testing, I am currently involved in a project that requires me to create a standalone environment for testing the web application. The main goal is to ensure the web application is easily testable ...

What is the process for embedding a single spa app into a basic HTML page?

Started off by creating a react app and then transforming it into a single spa react app using this tutorial. Upon hitting http://localhost:8080/org-app.js, I receive a response of the JavaScript files being loaded. Additionally, when I visit this link, t ...

Enhancing the appearance of the content editor with a personalized touch

I am working with a standard content editor that utilizes an iFrame as the text area. Upon changing dropdown options, it triggers the following command: idContent.document.execCommand(cmd,"",opt); Where "idContent" refers to the iFrame. One of the dropd ...

How can I extract several values from a child component in React?

Is there a way to retrieve two values in a single method of the Parent Component by passing props value from Child Component? What would be the best approach? Form.js (Child Component) // First method -> Extracting the suggestion value and passing i ...

Transferring information about service events to a controller in Angular

I am facing an issue with some audio elements in my service that listen for the "ended" event. I am looking for a way to pass this message to an angular controller. Currently, my service code looks like this: Audio.addEventListener "ended", (-> ...

Ensuring thoroughness in validation without the use of specific text strings

Implementing the assignment or assertion of never at the end of a function is a strategy commonly used in Typescript to ensure exhaustive checks at compile time. To enable the compiler to recognize this, explicit strings are needed for it to check against ...