Steps for storing a JSON string containing several objects into a JavaScript variable

I'm working with a JSON that contains multiple objects, and it's possible for this JSON string to have more data/objects than just three. My goal is to create an array of objects regardless of how much information is included.

[ {"endDate":"2017-04-18","nrC":2,"type":"CO","dataD":"2017-04-19","startDate":"2017-04-16"},  
  {"endDate":"2017-04-27","nrC":4,"type":"CP","dataD":"2017-04-23","startDate":"2017-03-26"},  
  {"endDate":"2017-04-27","nrC":7,"type":"CA","dataD":"2017-04-23","startDate":"2017-04-26"}
]
var USER_DAYS = {};

for(var i=0;i<json.length;i++){   
    var USER_DAYS = [  
      {
          id: json[i].nrC,
          date: json[i].dataD,
          title: json[i].type,
          start: new Date(json[i].startDate),
          end: new Date(json[i].endDate),
          allDay: true
      },            
    ];

    console.log(i); // displays 1, 2, 3
}

console.log(USER_DAYS) // shows only the last object from the json.

The JavaScript variable USER_DAYS should be an array containing n objects when printed, but currently only one object is being displayed in my console instead of the desired three.

I am looking to populate the USER_DAYS variable with all objects from the JSON provided.

Answer №1

With each iteration of the loop, a new array is created and the previous one is discarded.

To optimize performance, initialize the array outside the loop.

Add a new object to the array during each iteration of the loop.

// Use of ALL CAPS convention is typically reserved for constants. 
// Since you're not dealing with constants here, avoid using ALL CAPS
var userDays = []; // Define and initialize the array outside the loop
for (var i = 0; i < json.length; i++) {
    // It's important to note that you're creating an object named `user_day` inside the loop
    var userDay = {
        id: json[i].nrC,
        date: json[i].dataD,
        title: json[i].type,
        start: new Date(json[i].startDate),
        end: new Date(json[i].endDate),
        allDay: true
    };

    // Add the created object to the array
    userDays.push(userDay);
}
console.log(userDays);

Answer №2

It is important to avoid overwriting your variable in each iteration, like this:

USER_DAYS[i]   = {
                   id: json[i].nrC,
                   date: json[i].dataD,
                   title: json[i].type,
                   start: new Date(json[i].startDate),
                   end: new Date(json[i].endDate),
                   allDay: true
                 }

Make sure to define your Array before the for loop as shown below:

Here's an example:

var json = [{
    "endDate": "2017-04-18",
    "nrC": 2,
    "type": "CO",
    "dataD": "2017-04-19",
    "startDate": "2017-04-16"
  },
  {
    "endDate": "2017-04-27",
    "nrC": 4,
    "type": "CP",
    "dataD": "2017-04-23",
    "startDate": "2017-03-26"
  },
  {
    "endDate": "2017-04-27",
    "nrC": 7,
    "type": "CA",
    "dataD": "2017-04-23",
    "startDate": "2017-04-26"
  }
];

var USER_DAYS = [];

for (var i = 0; i < json.length; i++) {

  USER_DAYS[i] = {
    id: json[i].nrC,
    date: json[i].dataD,
    title: json[i].type,
    start: new Date(json[i].startDate),
    end: new Date(json[i].endDate),
    allDay: true
  };

  console.log(i); // prints 1,2,3
}

console.log(USER_DAYS) //prints the generated Array

Answer №3

To properly analyze the JSON string, make sure to utilize JSON.parse:

JSON.parse('[ {"endDate":"2019-07-14","numC":8,"category":"A","dateAdded":"2019-07-10","startDate":"2019-07-12"},{"endDate":"2019-08-25","numC":6,"category":"B","dateAdded":"2019-08-20","startDate":"2019-08-15"} ]')

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

Looking to bookmark Java links or a similar task?

Apologies for the lackluster title, as I am not well-versed in programming language and struggle to articulate my specific request... Allow me to explain: I frequently need to visit a particular website to conduct research (details below). I attempted usi ...

What is the best way to save an integer in HTML's localStorage instead of a string?

I've encountered an issue while using the localStorage feature in a game I'm developing. Specifically, the money variable should be increasing by 1 every second. Here's a snippet of my code: var money = 0; window.onload = function () { ...

Jquery adds a fun, wobbly effect to animations

I'm experiencing an issue with the animation I've implemented causing some slight shaking and wobbling of the text and certain elements which is affecting the overall look. You can view a live example of this behavior here: This problem specific ...

Update two distinct object properties using a singular reference in Vue's set method

I'm facing an issue while trying to insert an object into an array using the Vue.set function. The problem is that it adds the item to a different object with the same array property. Here's a snippet of my code: data() { return { ... ...

Tips for creating a clickable textbox

Does anyone know how to make a textbox clickable even when it is set as readonly. I'm looking for a way to make my textboxes clickable like buttons because I have some future plans for them. <input type="text" readonly value="Click me" id="clickm ...

Challenges with JavaScript arrays object

I am new to JavaScript and struggling with how to extract data from this array. Can you confirm if it is formatted correctly? Shown below is the console output of the array object: [] 0: Item {id: 0, symbol: "VBIV", boughtDate: "2018-07-22", company: "V ...

Is it beneficial to utilize components in order to streamline lengthy HTML code, regardless of whether the components do not repeat and do not require any props (such as in Vue or any other JavaScript library

In the Vue.js team project I am currently involved in, I have structured my code in the view as follows: component01 component02 ... There are more than 10 components in total. Each component represents a section of the landing page, consisting mostl ...

Updating a database with a loop of React Material UI toggle switches

I am trying to implement a material UI switch feature that can update the Active and De-Active status of users in the database directly from the Admin Panel. Currently, the database updates are functioning correctly when toggling the switches. However, th ...

Adding a background image to a box in MUI is a simple task that can enhance

I've been attempting to include a background image in the Box component of mui, but I can't seem to get it to work. Here is the code I've been using: const Main = () => { return ( <Box sx={{backgroundImage:'images/cove ...

Exploring React's State Management with useState

Having some trouble with my introductory React Use State practice, specifically when trying to implement a counter and a button for generating random user numbers Check out the code below: import React, { useState } from 'react' import './A ...

What is the best way to conceal an element by clicking anywhere other than on the element itself?

Currently, I am utilizing jQuery's toggle method to display or hide a page element when another specific page element is clicked. jQuery('a#mobile-search-icon).click(function(){ jQuery('#searchBox').toggle('slow'); }); ...

Controlling Javascript events

Currently, I am working on implementing an in-place editor using jQuery. The functionality is such that when you click on the text you wish to edit, it will replace the content with an input field, specifically a select tag. Everything seems to be functio ...

organizing various kinds of data values within an array

Within this array, I have two types of variables - an integer and a string. My goal is to sort the array either alphabetically or by the length of the string. However, it seems that the sorting algorithm is prioritizing the integer over the string. ...

Is there a way to obtain HTML code within a contentEditable DIV?

When working in a contentEditable-DIV, my goal is to extract the HTML code from the starting position (0) to the end position where the user has clicked. <div id="MyEditableId" contentEditable="true"> 1. Some text 123. <span style="background-c ...

unresponsive script caused by videoegg javascript code

Has anyone encountered a message like this before? "A script on this page might be occupied, or it could have stopped responding. You have the option to stop the script now, or you can wait to see if it finishes." No JavaScript errors are visible in the ...

Is there a way in Node.js to showcase a list of choices using console log and prompt the user to input an option from the list displayed through console log?

Is there a way to use Node.js to show a list of options through the console log and prompt the user to input an option from the list via console log? Expected behavior user@desktop:~$ node test.js Option 1 Option 2 Option 3 Select an option to proceed: ...

A step-by-step guide on closing a Bootstrap 5 Modal using JavaScript

Objective: I am trying to close a bootstrap 5 modal using JavaScript code after showing an alert message. Challenge: I am facing difficulty getting the function myFunction to work and subsequently closing the modal once the alert message is displayed ...

Toggle the visibility of a checkbox based on the JSON data

I have 4 check boxes that need to be dynamically displayed based on the value retrieved from my JSON. The JSON will only contain one checkbox name, and that specific checkbox should be shown to the user as checked. How can I achieve this functionality? Bel ...

Fixing issues with Ajax calls in Internet Explorer versions 7 and 8

Here is the Javascript code I have written: $("#login").click(function(){ username=$("#user_name").val(); password=$("#password").val(); $.ajax({ type: "POST", url: "login.php", data: "username="+username+"&passw ...

Transforming strings of HTML into objects in the DocX format

After developing a TypeScript script that transforms a JSON string into a Word Doc poster using Docx, I encountered a hurdle. Certain sections of the JSON may contain HTML tags, such as <br/>, <i>, <p>, and I need a way to pass the stri ...