Looking to create a loop that continues as long as a JSON dataset remains assigned to a specific variable

I've been trying to retrieve JSON data, but I seem to have hit a snag. I'm not sure where I went wrong or how to correct it.

[
{
"userId": 1,
"title": "A",
"body": "B"
},
{
"userId": 1,
"title": "C",
"body": "D"
},
{
"userId": 2,
"title": "E",
"body": "F"
},

function loadPost (y) {
    $.getJSON(  
    function(data){ 
    var i;
    while (y = data[i].userId) {
    $("#card").append(
        "<p><span class='postTilte'>" + data[i].title +
        "</span>"+ data[i].body + "</p>"
        )
    }}

When this is clicked, the function will execute and display the desired information based on the provided number for variable y.

Can anyone offer assistance?

Answer №1

When initializing the variable "i" is forgotten, an infinite loop may occur and it must be incremented correctly. See the example code below:

function loadPost (y) {
    $.getJSON(  
    function(data){ 
    var i =0 ;
    while (i<data.length) {
if(y = data[i].userId)
{
    $("#card").append(
        "<p><span class='postTilte'>" + data[i].title +
        "</span>"+ data[i].body + "</p>"
        )
    }
}
i++;
}

Answer №2

for (z = info[j].userId) {
    $("#container").append(
    "<h3><span class='articleTitle'>" + info[j].headline +
    "</span>"+ info[j].content + "</h3>")
    j++;    //increase value of j
}

Answer №3

Utilizing the Array function filter alongside forEach. (No need for i here!)

Check out the code on JSFiddle

var list = [{
    "userId": 1,
    "title": "A",
    "body": "B"
},
{
    "userId": 1,
    "title": "C",
    "body": "D"
},
{
    "userId": 2,
    "title": "E",
    "body": "F"
}]

loadPost(list, 1)

function loadPost(arr, y) {
    var result = ''
    arr.filter(function (val, idx, aa) {
        return val.userId === y
    }).forEach(function (elem) {
        result += '<p><span class="postTitle">' + elem.title +
            '</span>' + elem.body + '</p>'
    })
    $("#card").append(result);
}

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 JSON information into a datatable or a multi-dimensional array

Looking to deserialize a JSON file I receive from a URL using VB.NET or C#, with the data format as follows: "{"350.20 AAA": [], "350.200 BBB": [{"name":"arold","surname":"winter"}, {"na ...

Slideshow Display Suddenly Halts at the Last Image

I am currently working on a Bootstrap JS Carousel that showcases several images stored in the project folder. Each image's filepath is retrieved from an SQL Server database and displayed within the carousel. While the images are displaying correctly ...

Are you interested in implementing the switcher function in a React JS class component?

I am having trouble implementing the switcher method in my react app, which is built using class components. Can you provide guidance on how to utilize the useThemeSwitcher() function in class components? How can I integrate this function into my web app ...

Converting ArraysList to JSON format

I wrote the following code to output an ArrayList as JSON. However, when I executed the code, the output I received was: {uniteids:=[{"UniteId:":"gsheetyr","Message:":" The given user is already a member of the given DL.,"},{"UniteId:":"spokuri ","Messa ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (http://www.chartjs.org/docs/). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfull ...

Converting JSON data into an Angular object

I'm struggling to map the JSON data below to an Angular 7 object: [ { "id": "123456", "general": { "number": "123", "name": "my name 1", "description": "My description with <li> html tags ...

Best practices for making an AJAX call to fetch information from a database

I have a database containing a single table. The table includes columns for Company and Time, among others, with Company and Time being crucial. Users can make appointments by filling out a form. Within the form, there are 2 <select> elements - one ...

What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object. The main table is called sentinel and the secondary table is named sensor https://i.sstatic.net/1BrRq.png https://i.sstatic.net/3lOVD.png It can be observ ...

Maximizing the output of a foreach loop using json_encode

Working with a PHP result set, I am extracting values using a foreach loop. The extracted values are stored in an array called $summery[]. However, when trying to print the values, they are all printed at once. What I actually need is each value/result set ...

Using createStyles in TypeScript to align content with justifyContent

Within my toolbar, I have two icons positioned on the left end. At the moment, I am applying this specific styling approach: const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', }, appBar: ...

Getting the most out of the fastest-validator package: Implementing multiple patterns and custom messages

Utilizing the powerful fastest-validator library for validation purposes. I have a requirement where the password field must contain at least one character and one number. Along with this, I am in need of specific messages for validating these conditions ...

Passing the response from an AJAX request to JavaScript

When I call ajax to retrieve a value from an asp page and return it to the calling javascript, the code looks like this: function fetchNameFromSession() { xmlhttp = GetXmlHttpObject(); if (xmlhttp == null) { alert("Your browser does n ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...

Utilizing the dnd library to incorporate drag and drop functionality

I've encountered an issue with the code snippet below. Although I am able to drag elements, I am unable to drop them. How can I trigger the dropFunction when a drop occurs? Drag code: <div> <a class="button" ng-class= ...

Managing numerous validation issues received from a online service

Within my repository, I utilize a client to transmit an object as a JSON package to a web service. If validation fails, the web service will return JSON containing a list of errors. I am currently contemplating the best method to relay these errors back to ...

When testing, Redux form onSubmit returns an empty object for values

Is it possible to pass values to the onSubmit handler in order to test the append function? Currently, it always seems to be an empty object. Test Example: const store = createStore(combineReducers({ form: formReducer })); const setup = (newProps) => ...

Implementing JSON encoding for Swift parameters

Could you offer some guidance on passing the following parameters in Swift or Objective-C? let parameters = ["Access_Key":"0699DADD8A2B5FC2E8FF6FF5DDFE03EEDB3ED2132B29EA4F28","Packages":["Length":self.Length,"Type":"","Kg":self.Weight,"Height":se ...

Learn the position of a div element that appears following the lazy loading of images

I am struggling to make a div sticky below a set of lazy load images. The issue lies in the fact that the offset of the div keeps changing due to the lazy loading images pushing it down. There are 4 images with unknown heights, making it difficult to acc ...

Utilize jQuery to wrap text within <b> tags and separate them with <br> tags

Upon receiving output in html string format from services, I am presented with the following: "<html>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 : ABCD <br>key2 : 2016-10-18-18-38-29<br> ...

Using postMessage to communicate with the localstorage of an iframe from a separate domain

I have a question regarding the challenges of using localStorage for performance reasons and any potential workarounds. From what I gather, once a reference to localStorage is detected on a page (at compile time?), it blocks the thread to read data from di ...