Loop through a malfunctioning JSON structure

I am currently working on a script to loop through a JSON object with a fixed structure that cannot be modified.

However, I suspect the JSON is invalid because it lacks a key.

This is how my JSON looks:

{
    "0": {
        "name": "You",
        "message": "dwd"
    },
    "1": {
        "name": "You",
        "message": "asa"
    },
    "2": {
        "name": "You",
        "message": "this is the message that the user is faced with boi"
    },
    ...
}

I have a script in place but it doesn't seem to properly iterate over this object.

for (var key in greetings){
            name = greetings[key].name
            console.log(name)
            msg = greetings[key].message
            tag = '<ul>' + name + ' wrote: ' + message + '</ul>'
            ul = ul + tag
        }

Any assistance would be appreciated.

UPDATE:

Additional information: The greetings object comes from a server and is fetched using XMLHTTPRequest as shown below.

xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                greetings = JSON.parse(xhttp.responseText);
                console.log(greetings);
            }
        };

The reason for reassigning variables within the loop is to format each object in the list with its own HTML tag.

Answer №1

Patrick Bar was instrumental in identifying the issue of this code executing ahead of the async callback triggered by the server request. The problem has now been resolved, and I appreciate all the valuable feedback received.

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

Semantic UI (React): Transforming vertical menu into horizontal layout for mobile responsiveness

I have implemented a vertical menu using Semantic UI React. Here is the structure of my menu: <Grid> <Grid.Column mobile={16} tablet={5} computer={5}> <div className='ui secondary pointing menu vertical compact inherit&apos ...

"Prop serves as a blank slate within the child component of a React application

My current challenge involves integrating a search bar into a parent component. Despite successful logic in the console, I am experiencing a reduction in search results with each character entered into the search field. The issue arises when attempting to ...

Exploring the capabilities of useRef in executing a function on a dynamically created element within a React/Remix/Prisma environment

I've been trying to implement multiple useRef and useEffect instructions, but I'm facing difficulties in getting them to work together in this scenario. The code structure involves: Remix/React, fetching data from a database, displaying the data ...

Trigger the next button click event using jQuery

Is it possible to implement a slideshow on my website where clicking a button displays the relevant slide? My goal is to incorporate a timer that will automatically click the next button after 3 seconds, enabling the slideshow to transition automatically. ...

Problems with implementing JavaScript code in a WebView

I am currently working on an android WebView project where I have managed to change the background color to orange with this code snippet. @Override public void onPageFinished(WebView view, String url) { wv.loadUrl("jav ...

Guide on setting up a fresh MongoDB database with the Node.js driver

My goal is to establish a new Database in MongoDB by utilizing the Node JS driver. Despite attempting different methods, I encountered a situation where no databases were created (verified through the mongo shell and RoboMongo). Even more frustrating is th ...

Regular expression: Locate a string unless it is contained within another string

I am currently working on creating a regex pattern to analyze a CSS file and identify any occurrences of $, except when it is part of an attribute selector ($=, such as in [attr$=foo]). In simpler terms, I am aiming to locate a specific string unless it i ...

Error in jQuery when trying to access the src attribute of an image: "undefined src

Just started delving into jQuery. I'm trying to grab the image source and showcase it in a fixed division like a pop-up, along with the image title. However, I'm encountering difficulties in fetching the image source. My attempt with the .attr() ...

Using `new FormData(form)` to access form data without actually submitting the form

I'm facing an issue with my HTML form that has a file input. I need to handle the response from the form submission without refreshing the page. To achieve this, I've implemented an Ajax call to submit the form on my behalf. However, every time ...

Encountering an issue with jQuery where the element cannot be hidden

Having an issue with jQuery I am attempting to hide an element instantly using a function. Here is the code snippet: <!DOCTYPE html> <html> <head> <title>Test Page</title> </head> <body> <script src="https ...

Creating a spherical shape using random particles in three.js

Can anyone assist me in creating a random sphere using particles in three.js? I can create different shapes with particles, but I'm unsure how to generate them randomly. Here's my current code: // point cloud geometry var geometry = new THREE. ...

Why isn't my object updating its position when I input a new value?

<hmtl> <head> <!--<script src='main.js'></script>--> </head> <body> <canvas id='myCanvas'> </canvas> <script> function shape(x,y){ this.x=x; this.y=y; var canvas = document.get ...

Is it possible to run a web game on the same URL?

While working on quickly prototyping my ideas, I have been utilizing Express with Mongo and have successfully implemented a mongostore cookie storage system. Here's what I'm wondering: Can I keep everything happening on one page, specifically &a ...

How can I create an empty array with AngularJS?

Trying to retrieve an array object from a PHP file using AngularJS, the process seems to work but the array content is not showing up in the browser: Here is my PHP file: <?php include_once '../DAO/DAOadmin.php'; $list = DAOadmin::All(); ...

Transforming CSV files into JSON format using pyspark while applying filters and including extra columns

Suppose we have a CSV data file with the following headers: "CorrelationID", "Message", "EventTimeStamp", "Flag", "RandomColumns" 12345, "Hello", "2019-06-09 04:25:15", "True", ...

Viewing the information stored in a text file hosted on a web server

I need help enhancing the functionality of a webpage on my server. Specifically, I want to display the contents of a text file saved on the server. I am struggling with the syntax, but it seems to involve using Flask along with HTML and JavaScript function ...

Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what&ap ...

What is the process of importing an SVG file into Vue 3?

I attempted to follow this GitHub repository: https://github.com/visualfanatic/vue-svg-loader/tree/master Unfortunately, I encountered a version conflict with vue-template-compiler as it is designed for Vue 2. Next, I tried to use just the main repositor ...

Sort the observable data by a value returned from an API request

I am completely new to using RxJS and any assistance offered would be greatly appreciated! Within my component's HTML template, I am looking to create a radio button list. The values for this list are fetched from an observable using the async pipe. ...

Addressing the problem of refactoring in JavaScript when associating arguments with keys in MongoDB

I am facing a dilemma with two functions that are almost identical except for the value being set as indicated: function extracted_start(details, txt) { return FutureTasks.upsert({ number: details.number ...