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

Why is my React Native TouchableOpacity onPress function not functioning properly?

Embarking on my journey with React Native (or any JS framework for that matter), I decided to delve into creating a simple tap game. The concept is straightforward: tap on the blue square, watch it randomly relocate, and repeat the process. Here is a snipp ...

Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method. While the direct values ...

Retrieving online content and updating it upon reestablishing internet connection

Currently, I am in the process of developing an app that will feature a substantial amount of web content. My plan is to use Phone Gap build for its release; however, I intend to host all the content online and link to it from within the app. I have been c ...

What is the best way to leverage an existing user database and integrate user authentication into a fresh project?

I have recently taken on the task of revamping an established project by creating a brand new frontend from scratch. After careful consideration, I have opted to develop a straightforward Vue/Node.JS project. Within the current framework lies a Postgres d ...

Struggling to make vue-i18n function properly with nuxt generate?

In an effort to enhance my skills, I am creating a small Nuxt project from scratch. While the project runs smoothly on the local server, I have encountered an issue with the language switcher not updating the translation fields when using nuxt generate. U ...

whenever I execute my `node file.js 1 23 44` command, nothing is displayed on the screen

When I execute node file.js 1 23 45, the expected output is supposed to be One TwoThree FourFive. However, for some unknown reason, nothing is being printed out. The script appears to run without any errors, but the desired output is just not appearing. ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

A guide to retrieving all keys from a JSON object in Javascript

{"data": {"characters":[ {"name":["Harry Potter"],"age":["18"],"gender":["Male"]}, {"name":["Hermione Granger"],"age":["18"],"gender":["Female"]} ]} } In the given JSON data, I am interested in retrieving the keys like name, age, gender for ea ...

What is the best way to retrieve the value of an UL LI element using jQuery

I'm struggling to retrieve the value of a ul li listbox in a function, and I can't seem to figure out how. Here is my code: <ul class="dropdown-menu" id="newloc"> <?php $res_add = DB::table('res_br')-& ...

Unable to display the popup modal dialog on my Rails application

I currently have two models, Post and Comment. A Post has many Comments and a Comment belongs to a Post. Everything is functioning properly with the creation of posts and comments for those posts. Now, I have a new requirement where when clicking on "crea ...

Selecting a random string element from an array using C programming

I'm still learning my way around C, although I'm quite experienced in programming. My current project involves developing a program that prompts for user input and then outputs a predetermined string saved in an array. What I aim to achieve is s ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

Tips for utilizing the value obtained from an AJAX URL in Yii

Recently I started using Yii and I have a form with a combo box and a text field. What I want to achieve is changing the value of the text field based on the selection made in the combo box. I am able to get an AJAX url by changing the combo box value, and ...

How can I convert the JSON array response from the API, which is of type string, back into an array?

Is there a way to change a string type array back into an array? var arr = '[ "abc", "def"]'; console.log(typeof arr) ==> String How can I convert it back into an array format? I'm receiving this string-formatted array from an API r ...

The Year as a Reference Point

I came across an interesting issue while working with dictionaries and JSON in sessionStorage. Initially, I had a dictionary structured like this: "name" : { "2016" : { "1" : "info" } } After successfully adding it to sessionS ...

Dynamic height of a fixed-positioned Div

I encountered an issue with a Fixed positioned DIV that has dynamically appended content using jQuery. Once the height of the DIV exceeds the screen size, I am unable to view the contents at the bottom of the DIV without zooming in using the browser' ...

Creating a copy of a div using jQuery's Clone method

I need help figuring out how to clone a div without copying its value. I've attempted various methods, but they all seem to include the value in the cloned element. This is the jQuery function I am currently using: $('#add_more').click(fu ...

Issue with React setState not triggering when switching between tabs in Material UI. Attempted to hide using a div with display set to none

Every time I switch between Material UI Tabs, the state gets cleared and does not persist. Check out this link for more information I have attempted different solutions: Using React Context to pass in the React State, but the issue remains unresolved T ...

Issue: ParserError encountered due to a Syntax Error found at line 1, column 32

As a beginner in programming, I am encountering an issue. When I run "npm run build" in the Terminal to compress my project in React.js, I encounter this error. Interestingly, I have previously created another project without facing this problem, and I can ...