Transforming a JSON string into an object within a variable amount of nested JSON structures

I'm encountering an issue with modifying JSON strings within JSON objects for varying numbers of objects. Allow me to elaborate further with my code and explanations.

I have a factory that supplies JSON objects

//Factory for products
app.factory('productsFactory', ['$http', '$location', function($http, $location){
    var factory = {};
    factory.getlatestProductsList = function(n){
        return $http.get($location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n);
    }
    return factory;
}]);

This factory returns an uncertain number of objects

0: Object
active: "1"
alias: "baumbach-circle"
date_c: "2016-01-06 08:09:54"
date_u: null
description: "Corrupti fugit iste quo sunt quidem voluptatibus dolorem. Eos velit architecto veritatis doloribus. Corporis sequi cupiditate possimus voluptates ut consequatur. Accusantium libero qui est sunt et."
id_category: "46"
id_product: "25"
id_user: "177"
images: "[{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?63763","image":"http:\/\/lorempixel.com\/1024\/768\/?52630","position":0},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?99795","image":"http:\/\/lorempixel.com\/1024\/768\/?84669","position":1},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?17506","image":"http:\/\/lorempixel.com\/1024\/768\/?88926","position":2},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?73869","image":"http:\/\/lorempixel.com\/1024\/768\/?91917","position":3},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?70019","image":"http:\/\/lorempixel.com\/1024\/768\/?18509","position":4}]"
name: "Baumbach Circle"
__proto__: Object
1: Object
active: "1"
alias: "elta-road"
date_c: "2016-01-06 08:09:53"
date_u: null
description: "Culpa perferendis dolores rerum deleniti vero cumque. Similique explicabo beatae est quo sit nisi. Et a voluptatem nihil in. Voluptates modi qui est ducimus corrupti."
id_category: "46"
id_product: "24"
id_user: "73"
images: "[{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?53746","image":"http:\/\/lorempixel.com\/1024\/768\/?49502","position":0},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?75052","image":"http:\/\/lorempixel.com\/1024\/768\/?77727","position":1},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?32463","image":"http:\/\/lorempixel.com\/1024\/768\/?76121","position":2},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?61377","image":"http:\/\/lorempixel.com\/1024\/768\/?89434","position":3},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?86873","image":"http:\/\/lorempixel.com\/1024\/768\/?82513","position":4}]"
name: "Elta Road"
__proto__: Object

The issue arises from the images JSON being formatted as a string, requiring me to utilize JSON.parse (at least I believe so, given my limited experience) to convert them into JSON

My inquiry is: Is there a simple and elegant method to parse all image data into JSON or must I resort to using forEach? If so, how would the code implementation look like? I aim to achieve this functionality within the factory to avoid redundancy in each controller calling upon it.

If you require any additional information, please do not hesitate to ask and I will gladly provide it. Thank you in advance.

Answer №1

You have the ability to modify the response received from the $http service before sending it back.

app.factory('productsFactory', ['$http', '$location', function($http, $location){
    var factory = {};
    factory.getlatestProductsList = function(n){
        var url = $location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n;
        return $http({
            method: 'GET',
            url: url
        }).then(function successCallback(response) {
            // You can customize the response here by parsing or editing it
            return response ;
        }, function errorCallback(response) {

        });
    }
    return factory;
}]); 

Answer №2

If you utilize the fact that $http gives back a promise, you can perform some data processing before returning the promise. Please inform me if this approach suits your needs, or if you require assistance in ES5.

factory.getlatestProductsList = function(n){
    return $http.get($location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n)
    .then(data => data.map(elem => {
       var tmp = Json.parse(elem.images);
       elem.images = tmp
       return elem;
    }));

In ES5:

factory.getlatestProductsList = function(n){
    return $http.get($location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n)
    .then(function(data) {
       return data.map(function(elem) {
         var tmp = Json.parse(elem.images);
         elem.images = tmp
         return elem;
       });
    });

Answer №3

Here is a code snippet for creating a factory in AngularJS:

//Factory for products
app.factory('productsFactory', ['$http', '$location', function($http, $location){
    var factory = {};
    factory.getlatestProductsList = function(n){
        var url = $location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n;
        return $http({
            method: 'GET',
            url: url
        }).then(function successCallback(response) {
            var pros = response.data;
            pros.forEach(function(item){
                var pictures = JSON.parse(item.images);
                delete item.images;
                item.images = pictures;
            })
            return pros;
        },function errorCallback(response) {
            console.log('error fetching latest products: ' + response);
        });
    }
    return factory;
}]);

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

Encountering a 404 error for core.js and browser.js while loading an Angular 2 app through system.src.js

I am new to Angular2 and have followed the Angular2 quickstart and tutorial to get started. Just to provide some context, when a user clicks on a link in the top navigation bar of my webapp, it triggers a server side request. The resulting page returned t ...

Invoke the ng-click function within the ng-change function

Just starting out with angularjs and I have a question. I am currently using single select and I want to retrieve the value selected and based on that value, perform an action. For example, if the value is "DELETE" then I would like to trigger the ng-clic ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...

Disabling the submit button on an MC form - step by step guide

In order to create a multiple-choice question with radio buttons, each question must have only one answer choice. Each question should provide three options for the user to select from. It is necessary to validate whether the user has answered every questi ...

Loop through the .getJSON response using jQuery

I've searched high and low for an answer to my question, but I can't seem to find one. My issue is with iterating over a JSON array (and its object) using jQuery's .each() method to print out all the values. Here is the JSON structure: { ...

The conditional statement does not align with my Regular Expression

I'm experiencing a peculiar issue with my regular expression matching in the code snippet provided. Even though the alert confirms a match between the strings, the if statement fails to trigger. Any insights on why this might be happening? Appreciate ...

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...

Tips for retrieving arguments within a method called from a template in vue.js?

Here is an example where I am attempting to call a method from the template and pass in some arguments. How can I access those arguments from within the method? Snippet from script: methods: { showBinaries(job, id) { let test_url = process.en ...

Navigating Between Pages with Parameters in Ionic 2 (starter app)

I have an Ionic 2 project with a blank template containing a page that displays a list. Upon clicking on an item in the list, the user should be able to view more details about that specific item. Below are the files related to the list: list.html: <i ...

Creating stylish error labels using Materialize CSS

While Materialize has built-in support for validating input fields like email, I am looking to implement real-time validation for password inputs as well. This would involve dynamically adding error or success labels using JavaScript. Unfortunately, my at ...

Toggle the display of data in an angular table with a button click

Having trouble implementing a sorting feature in Angular where I can filter friends by age. The goal is to be able to click on one of three buttons with ages and have only friends with that age displayed. For example: Initially, all friends are shown. Cl ...

guiding user immediately to blog post upon successful login

I recently created a blog with a customized URL like instead of the traditional . Now, my dilemma is that I want to share this URL and have it redirect users to the login page if they are not logged in. Once they log in, I would like them to be redirect ...

How can I utilize a variable in a v-for loop as a label for a q-btn in Vue.js?

I have a list: myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] I'd like to generate buttons using this list where the label corresponds to the number: <q-btn v-for="number in myList" v-bind:key="number" color="primary" label=&q ...

How to Make a Div Tag Fade Effect with JavaScript in an External File

*** New Team Member Notice *** I'm currently working on an assignment and trying to implement a simple fade effect on a box. While it seems like this should be straightforward, I'm encountering some obstacles. Currently, the button causes the bo ...

There seems to be an issue with the HighCharts chart export feature as it is not showing the Navigator graph

We are currently using HighCharts version 4.2.2 http://api.highcharts.com/highcharts/exporting While going through their exporting documentation, I made a decision to not utilize their default menu dropdown. Instead, I only needed access to the .exportCh ...

Creating a jsp page content with jquery and retrieving request parameters

I am facing an issue with my JSP page where I need to pass the value of request.getParameter("cfgname") to another content page so that it loads correctly. Currently, the code is displaying null instead of the parameter. This is the main JSP page with par ...

What is the best way to separate one dropdown area from another dropdown area?

I have two dropdown menus where, when an option with the value "other" is clicked, it generates a text area just below the dropdown menu. Both sections are functioning correctly, but I had to create separate parent wrappers for each in order to do so. How ...

From Vanilla Javascript to ES6 Spread Operator

I recently incorporated a script into my project that utilizes the ES6 spread operator to extract parameters from the URL. However, I encountered an issue when I realized that the project does not support ES6 syntax. While it is straightforward to apply t ...

Create an Ajax request function to execute a PHP function, for those just starting out

I came across a JS-Jquery file that almost meets my needs. It currently calls a PHP function when a checkbox is clicked, and now I want to add another checkbox that will call a different PHP function. My initial attempt was to copy the existing function a ...

JavaScript: Remove just the specific user input without affecting the rest of the HTML block

I'm facing a dilemma with deleting a specific user input without removing the entire HTML block. I know that the delete button triggers on the HTML ID 'noteDelete', which is the parent of each user input. However, I'm unsure about how t ...