What is the best way to create a JavaScript array after fetching data from an AJAX request that returns a JSON array?

When I make an ajax call that returns JSON data, my goal is to extract and organize this data into a new JavaScript array through looping.

This is a snippet of the JSON data returned:

{
    query: [ ],
    products: 
[
    
{
    title: "title 1",
    price: "6.00",
    magazine: "magazine name 1",
    image: "/p/c/pc_90_cover.jpg",
    type: "Magazine",
    market: "Technology",
    zinio: "http://www.zinio.com",
    newsstand: "http://www.link1.php"
    },

    
{
    title: "title 2",
    price: "6.00",
    magazine: "magazine name 2",
    image: "/p/c/pc_90_cover.jpg",
    type: "Magazine",
    market: "Technology",
    zinio: "http://www.zinio.com",
    newsstand: "http://www.link2.php"
    },

    
{
    title: "title 3",
    price: "6.00",
    magazine: "magazine name 3",
    image: "/p/c/pc_90_cover.jpg",
    type: "Magazine",
    market: "Technology",
    zinio: "http://www.zinio.com",
    newsstand: "http://www.link3.php"
    }
    ]

}

I'm struggling with how to properly loop through this JSON data in JavaScript. Here's what I have attempted so far, although it needs improvement as my JavaScript skills are not the strongest:


var allProducts = $.get("http://localhost:8888/imagine-publishing/web/app_dev.php/api/v1/search/search.json?query=pho", function(data) {

    var arrProducts = [];

    for (var i = 0; i < data.products.length; i++) {
        var product = data.products[i];
        
        var item = {
            title: product.title,
            url: product.url, 
            label: product.title, 
            magazine: product.magazine,
            image: product.imageThumb,
            newsstand: product.newsstand,
            googleplay: product.googleplay,
            kindle: product.kindle, 
            barnesnoble: product.barnesnoble,
            zinio: product.zinio, 
            kobo: product.kobo, 
            waterstones: product.waterstones, 
            type: product.type, 
            brandurl: product.brandurl 
        };

        arrProducts.push(item);
    }

    console.log(arrProducts);

});

Answer №1

If the JSON is being served with the proper Content-Type of application/json, jQuery will handle the parsing of the data and then fill the initial parameter of the callback function with the outcome.

let productArray = result.data;

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

What is the best way to implement the useCallback hook in Svelte?

When utilizing the useCallback hook in React, my code block appears like this. However, I am now looking to use the same function in Svelte but want to incorporate it within a useCallback hook. Are there any alternatives for achieving this in Svelte? con ...

Seeking for the smallest value in my JSON dataset and determining the total number of records per page in my JSON dataset

Inside my controller class, I have a Pojo class named sampledata. My goal is to retrieve the "total _page" field and lower the "id" from JSON data. ///Here is an example of the client's JSON data {"example":1,"page":1,total_page":1,"data":[{"id":1,"f ...

What is the reason for the visibility of my API key when utilizing next.js alongside environment variables?

I recently went through the next.js documentation and implemented a custom API key on my now server. However, I encountered an issue where when I execute now dev and navigate to the sources tab, my API key is visible. https://i.stack.imgur.com/kZvo9.jpg ...

Activate browser scrollbar functionality

Below is the HTML code snippet: <html> <head> <style> #parent { position : absolute; width : 500px; height : 500px; } #top { position : absolute; width : 100%; height: 100%; z-index : 5; } #bottom { position : absolute; width : 100%; ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

Plotting Polyline Path on Google Maps using Angular

I am attempting to create a simple polyline connecting two markers using Angular-google-maps. While I have successfully positioned my two markers, I am encountering some complexity when trying to draw a polyline between them. It seems that my logic may no ...

Add drop caps to every individual word within a hyperlink

Is there a way to recreate the menu effect similar to using CSS fonts and drop caps for each word? I'm aware of the CSS code: p.introduction:first-letter { font-size : 300%; } that enlarges the first character of the first word, but I want this ef ...

The issue with Jquery getJSON not functioning properly across different websites

I am having an issue with a JavaScript code that fetches JSON data. It works perfectly fine when run locally, but does not function properly when accessed from another website. Below is the script: $(function(){ var aT = new AjaxTest(); aT.getJso ...

Enhance the functionality of the custom transaction form in NetSuite by incorporating new actions

I'm currently working on incorporating a new menu option into the "Actions" menu within a custom transaction form in NetSuite. While I can successfully see my selection in the Actions Menu on the form, I'm running into an issue with triggering th ...

Encountering a problem retrieving information from a nested JSON array

When fetching data from an API in JSON format, I encountered a successful response. However, the issue lies in extracting direct values without keys. Let me display the response first: Response { "message": "Notification Sent Successfully.", "success ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

What is the syntax for creating a JSON array in Kotlin?

As a beginner in Kotlin and Android Studio, I am grappling with how to declare a JSON array within a data class to store data retrieved from my API. The JSON structure is quite complex, and I am unsure of the correct way to declare an array of JSON objects ...

Issue with ServiceStack TypeSerializer.DeserializeFromString not handling C# nullable types correctly

Has a bug been identified in the ServiceStack method TypeSerializer.DeserializeFromString when handling nullable types? Is this a known issue, and if so, is there a fix or workaround available? Here is an example of code that utilizes a JsConfig scope to ...

First render does not define useEffect

Why am I experiencing an issue here? Whenever I attempt to retrieve data from my API, it initially returns undefined during the first render, but subsequent renders work correctly. const [data, setData] = useState([]) useEffect(() => { const fe ...

What is the process for executing Selenium IDE scripts in Selenium RC?

As a newcomer to using the selenium testing tool, I am seeking guidance on running selenium IDE scripts within selenium RC. I would greatly appreciate examples and screenshots to help me better understand the process. ...

Unpacking JSON data with flexible data format

When consuming a JSON API in C#, I encountered an issue where the response's data structure varies based on the number of results returned from the query. To deserialize the response, I am using JSON.NET. The JSON returned by the API is as follows: ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

Guide on utilizing the JSON string to update and obtain fresh information

My goal is to continuously send a JSON string {"latitude":53.86897577,"longitude":10.66560449,"formatted":"24.04.2015 16:26:35","route":4} to the server every minute, but I keep receiving the same data. How can I ensure that I always get new data in the JS ...

Uploading a single image using JSON in an MVC API

How can I upload an image as JSON in an API? I need to upload a file to the server folder and save the file path in an object of a class after uploading the image. var data = $('#myForm').serialize(); $.ajax({ url: "/api/CompaniesApi/"+id, ...