JavaScript seems to have difficulty correctly parsing objects from JSON

Having trouble populating a Repeat Box with objects from a JSON document. Despite my efforts, it keeps duplicating the first item instead of adding each one individually. Any ideas on what might be causing this issue?

Below is the code I am currently using to extract data from the JSON document.

function Project_WebClient1_OnSyndicationSuccess(e){
      var FactsArray = [];
    var parsedResponse = JSON.parse(this.responseText);
    var numOfFacts = parsedResponse.results.length;
    for (var i = 0; i < numOfFacts; i++) {
        var FactsObject = {};
        FactsObject.heading = parsedResponse.results[i].heading;
        FactsObject.ReleaseDate = parsedResponse.results[i].ReleaseDate;   
        FactsObject.url = parsedResponse.results[i].url;      
        FactsArray.push(FactsObject);
        log(FactsObject.heading);
    }
            Pages.pgFundInfo.RepeatBox1.dataSource = FactsArray;
            Pages.pgFundInfo.RepeatBox1.refresh();
Data.notify("Data.FactSheets_OutDSetFactSheets.FactSheetsId");
}

Provided below is the JSON Document:

{
    "results": [
        {
            "FactFile": {
                "__type": "File",
                "name": "Sept2015.pdf",
                "url": "http://files.sample.com/Sept2015.pdf"
            },
            "Heading": "Medium Growth September",
            "ReleaseDate": {
                "__type": "Date",
                "iso": "2015-09-30T06:29:00.000Z"
            },
            "createdAt": "2015-10-31T06:28:03.189Z",
            "objectId": "XUS4guS8Hu",
            "updatedAt": "2015-11-04T10:00:37.092Z"
        },
       ...
    ]
}

Although the correct number of results are being fetched, the Repeat Box displays them all using the data from the initial entry only. Can you point out any errors within my for loop implementation?

Answer №1

After analyzing your JSON document, this section of your loop

FactsObject.heading = parsedResponse.results[i].heading;
FactsObject.ReleaseDate = parsedResponse.results[i].ReleaseDate;   
FactsObject.url = parsedResponse.results[i].url;  

needs to be adjusted as follows

FactsObject.heading = parsedResponse.results[i].Heading; // make sure the H is capitalized
FactsObject.ReleaseDate = parsedResponse.results[i].ReleaseDate; // consider using the .iso attribute for date assignment  
FactsObject.url = parsedResponse.results[i].FactFile.url;  // pay attention to the FactFile property    

If not, you may receive undefined results.

Unfortunately, the issue causing only the first item to be retrieved instead of each individual one is unclear at this time.

update:

Executing the following code snippet

for (var i = 0, len = parsedResponse.results.length; i < len; i++) {
    console.log(parsedResponse.results[i]);
}

demonstrates that each item is logged individually and not just the first item repeatedly.

Refer to http://jsfiddle.net/q2burjk3/

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

Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client. There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed ...

Tips for Nesting Iterations in Java for JSONobjects

Currently, I have a JSON object called Station. I am using the keys() method to iterate over it to extract key-value pairs. However, I realize that I also need to iterate over the values themselves in order to capture every element of the value section. He ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

Retrieving visual information from Google Street View entity

Looking for a solution to extract imagery from the Google Street View panorama within a web page? In my program, I navigate specific routes using Google Street View's javascript API controlled by an embedded Java applet on the same page. I am seeking ...

What methods can be used to get npx to execute a JavaScript cli script on a Windows operating system

The Issue - While my npx scaffolding script runs smoothly on Linux, it encounters difficulties on Windows. I've noticed that many packages run flawlessly on Windows, but the difference in their operations remains elusive to me. Even after consulting A ...

Creating a dynamic star rating system using CSS

A unique code pen project showcasing a pure css star rating interface can be found at: https://codepen.io/yaworek/pen/JJpEaZ Below is the custom css part: /*** * Custom Pure CSS Star Rating Widget for Bootstrap 4 * * www.TheMastercut.co * ***/ ...

Decompressing Array in Vala/C

I need to input data using a text file that I'm piping in on my university's server. With two double values, a one-dimensional double array, and a two-dimensional double matrix, how can I import this into variables? Thank you so much for your h ...

All API endpoints must be accessed with a jwt token

After diving into the nextjs documentation, I stumbled upon something interesting. import { getToken } from "next-auth/jwt" const secret = process.env.NEXTAUTH_SECRET export default async function handler(req, res) { // if using `NEXTAUTH_SEC ...

`Misconceptions in understanding AngularJS directives`

I am currently working on a new app that includes both a header and main view, utilizing directives. At first, I had the directive in its own file but decided to relocate it into app.js in order to resolve an issue. Throughout this process, I have experim ...

The tooltips on a resized jQuery Flot chart are displaying in the incorrect location

Currently, I am utilizing the flot library for my chart. I am facing an issue with getting the correct tooltips to display when I scale the chart using this CSS rule: transform: scale(0.7); The flot source relies on the function findNearbyItem to locate ...

Prevent the execution of a Javascript function if it is already in progress

I've developed a function that retrieves records from a third party, and this function runs every 10 seconds. However, as I debug through Firefox, I notice a long queue of ajax requests. I'm contemplating including a statement that can signal to ...

Creating a backup link for a video player component in NextJs

My aim is to make sure that two video player components in a NextJS application can still access and play videos even when the application is running locally using npm run dev without an internet connection. Currently, these two components.. <HoverVi ...

Passing the contents of a datatable as parameters to a PHP script

I am facing a challenge with my datatable that has two columns, "Name" and "Age". After populating the datatable using Ajax, I create a button for each row. The goal is to send the "Name" and "Age" fields of the clicked row to a PHP script, which will then ...

Having trouble retrieving information from the database using socket.io and node.js

As a beginner in node.js and socket.io, I am experimenting with my simple project to fetch data from a database. My index.html serves as a real-time chat example using socket.io with a basic ajax request. <!doctype html> <html> <head> ...

Achieve Dual Functionality with Vue.JS Button within a Parent Element

My parent component structure looks like this: <template> <b-container> <b-modal id="uw-qb-add-item-modal" ref="uw-qb-add-item-modal" title="Enter Item Number" @ok="handleNewItem"> <f ...

The functionality of tinymce setContent can only be activated by directly clicking on it

Everything is running smoothly with the code below: $('.atitle').on('click', function(){ console.log('323'); tinymce.get("ed").setContent("<p>lorem ipsum</p>"); // it's working ...

Nested loops with synchronous calls running in parallel

Is there a way to make synchronous calls in two nested 'for' loops in Node.JS? I have an Asynchronous call, but I am unsure how to modify it to work synchronously and go to the next iteration when create_db is done! var new_items = []; f ...

Unpredictable Dependency Outcomes in Node.js

Encountering a warning while running yarn install where all dependencies are installed, but a specific warning is triggered: Warning: Pattern ["esprima-fb@~3001.0001.0000-dev-harmony-fb"] is attempting to unpack in the same destination "/Users/Me/Librar ...

The autocomplete functionality with ajax is currently malfunctioning

<script> function autocomplet1() { var min_length = 0; // minimum characters to display the autocomplete var keyword = $('#select01').val(); if (keyword.length >= min_length) { $.ajax({ url: 'barcode ...

Is Ajax still a popular choice for developing web applications?

Currently, I am developing a comprehensive ajax-based web application and have been investigating various frameworks for SEO optimization and history tracking. During my research, I came across an interesting framework at Although it seems promising, I no ...