What is the best way to navigate through a JavaScript array?

After making an ajax call, I received the following output:

"total":"3",
"data":[{   "id":"4242",
            "title":"Yeah Lets Go!",
            "created":"1274700584",
            "created_formated":"2010-07-24 13:19:24",
            "path":"http:\/\/domain.com\/yeah"
        }]

The output contains three items in an array. I need to iterate through them and generate HTML output on the page like this:

Yeah Lets Go! (which is a link to http:www.domain.com/yeah)
Created: 2010-07-24 13:19:24

I'm having trouble figuring this out.

Edit 1:
Currently, I only get the raw output after clicking the link. How can I make it show on page load instead of making an ajax call when clicking the link?

Edit 2:
I managed to output everything at once. But I'm still struggling with converting it into actual HTML. The current output is:

"total":"3",
"data":[{
            "id":"4242",
            "title":"Yeah Lets Go!",
            "created":"1274700584",
            "created_formated":"2010-07-24 13:19:24",
            "path":"http:\/\/domain.com\/yeah"
        }
        {
            "id":"4242",
            "title":"Yeah Lets Go!222",
            "created":"1274700584",
            "created_formated":"2010-07-24 13:19:24",
            "path":"http:\/\/domain.com\/yeah222"
        }
        {
            "id":"4242",
            "title":"Yeah Lets Go!333",
            "created":"1274700584",
            "created_formated":"2010-07-24 13:19:24",
            "path":"http:\/\/domain.com\/yeah333"
        }
]}

I want to display this in a list format with the title, link, and creation date.

Edit 3 after answer from Luca Matteis:
I'm even more confused now.

The JSON string is a result of the following code:

$('a.link').click(function() {
        var item_id = $(this).attr("href").split('#')[1];
        $.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', 
                null, 
                function(data, status, xhr) {
                    $('#contentCell').html(data);
                }
        );

To proceed, should I use something like:

var html = eval(data); 

and then follow Luca Matteis suggestion?

Answer №1

Initially, this appears to be a JSON string that needs to be deserialized into an actual JavaScript object (refer to json.org for guidance).

After converting the data to native JavaScript, the following code snippet can be utilized:

let output = '';
for(let i=0; i < object.data.length; i++) {
    output += '<a href="'+object.data[i].link+'">'+object.data[i].title+'</a><br>';
    output += 'Published: '+ object.data[i].date;
}

Answer №2

Well, now my confusion has reached a whole new level.

The JSON string mentioned is extracted from the following code snippet:

$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', null, function(data, status, xhr) {
$('#contentCell').html(data);
});

So, it seems like I would have to use something like this:

var html = eval(data); 

After that, should I follow the suggestion made by Luca Matteis?

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

Determine the sequence of a div based on its class

Here is the code snippet I am working with: <div class="test"></div> <div class="test"></div> <div class="test"></div> <input type="button" class="button" value="get number"> <div class="test"></div> & ...

ReactJS Components failing to load on initial site visit, only appearing after refreshing for the second time

var img; var dateFormat = require('dateformat'); var count; let arrayIMG = [] var storage = firebase.storage(); var storeRef = storage.ref('images/') const config = { ... }; if (!firebase.apps. ...

Use percentages for the width in CSS and pixels for the height, ensuring that both dimensions are equal

I'm attempting to create a square that adjusts its size according to the screen size. Currently, I have the width set to 25%. Is there a way to ensure that the height remains the same length in pixels as the width? Appreciate any assistance on this ...

An error of type 'System.Web.HttpException' occurred during the file upload process to the server

Recently, I have started learning about asp.net, ajax, and c#. I am attempting to save an image on the server using the example below: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> ...

Redirect middleware for Next.js

I am currently working on implementing a log-in/log-out feature in my project using nextjs, redux-saga, and mui libraries. // middleware.ts import { NextRequest, NextResponse } from 'next/server'; import { RequestCookies } from 'next/dist/c ...

Can we find a jQuery AJAX equivalent to the 'finally' block in regular JavaScript?

Is there an equivalent of Java's 'finally' in jQuery AJAX calls? I have this code snippet here. Inside my always, I intentionally throw an exception, but I want it to always proceed to the then() method. call.xmlHttpReq = $.ajax({ ...

Ajax Complete adds Jquery two times in a row

I have a simple ajax complete call that is designed to add some text after an ajax load finishes. However, I'm encountering an issue where the information is sometimes displayed multiple times. I suspect there might be something missing in my approach ...

What are the recommended guidelines for organizing files in an NPM package for front-end development?

I am creating an NPM package for the front-end and I'm trying to figure out the optimal file structure. My package consists of a code.js file as well as a code.min.js file. Should these files be located in the root directory, a dist folder, or a src f ...

Another option instead of using `:` to choose all items

When working with np.arange(3)[:] , the colon signifies that all elements from the specific dimension are being requested. However, there is a need for flexibility in selecting which elements are desired. Consider the following function: def selectItems( ...

I require the variable to be accessible from all corners

Is there a way to access the variable "finalPrice" in a different function? I'm trying to achieve this and could use some guidance. function available(id){ $.ajax({ method:"GET", }).done(function(data){ for( ...

Utilizing JavaScript to Incorporate Node Packages

Sorry for the basic question, as I am fairly new to web development and JavaScript. I am trying to utilize a package that I installed via npm called shopify-buy by following the instructions provided at: The package is located in my node_modules director ...

Syntax error encountered with the null-coalescing operator (`??`)

Encountering Syntax Errors After Upgrading Angular Plugin I am facing some syntax errors after attempting to upgrade a plugin in a system that was originally developed by someone else. Although I am relatively new to Angular, I tried to simply replace the ...

Switching over a function from jQuery to Mootools

Here is a snippet of code used to refresh a specific DIV by making a request for data. The current function works as intended, but we are looking to migrate to Mootools. JavaScript Code: <script> jQuery.noConflict(); (function(jQuery) { jQuery ...

Count of each occurrence of terms

Consider an array a[n][2], where n can reach a maximum of 10^5. This array represents n subjects and n students, all numbered from 1 to n. The values of a[i][0] and a[i][1] (1 <= i <= n) indicate that in the i-th subject, all students passing are wi ...

The method this.$refs.myProperty.refresh cannot be invoked as it is not a valid

I have added a reference value 'callingTable' to a vue-data-table (using vuetify) like so: <v-data-table :headers="callingTableHeaders" :items="getCallingDetails" class="elevation-1" ref="callingTable&quo ...

The functionality of the Ajax call ceases to function properly on mobile devices after a period of time

I'm currently developing a mobile application using Cordova, AngularJS, and jQuery. My issue lies in trying to retrieve two files from the same directory. The first file retrieval is successful and occurs immediately after the page loads. However, t ...

Discover the nearest class and smoothly expand it with the slideDown function in jQuery

Hey there, I'm working on implementing a "View More" button on my page. The button will reveal another unordered list that currently has the class of "hidden-list". When the user clicks on "View More", I want it to slideToggle the hidden-list element ...

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

Having trouble importing a variable from a precompiled library in TypeScript JavaScript

Here is the content of my package.json file: { "name": "deep-playground-prototype", "version": "2016.3.10", "description": "", "private": true, "scripts": { "clean": "rimraf dist", "start": "npm run serve-watch", "prep": "browserify ...

Exploring Ways to Modify a .txt File with Javascript or jQuery Forms

Looking for a way to access a .txt file offline in the browser and display its data in different form fields for each line. Any tutorials available for this? ...