Include a fresh attribute to a current JSON within a FOR loop

My goal is to populate a bootstrap-carousel using a more detailed JSON file pulled from a database. To illustrate, here is an example of my old JSON structure:

old.json

[
{"screen": [{
    "img" : "../static/images/product/34.jpg",
    "price": "Rs 100",
    "href": "#mobile/1234"
},{

    "img": "../static/images/product/34.jpg",
    "price": "Rs 101",
    "href":"#mobile/1234"
},...

]},
 {"screen": [{
    "img" : "../static/images/product/34.jpg",
    "price": "Rs 100",
    "href": "#mobile/1234"
},{

    "img": "../static/images/product/34.jpg",
    "price": "Rs 101",
    "href":"#mobile/1234"
},...

]}
]

Now, I am aiming to update it with a new.JSON that provides more detailed information.

new.JSON

[
 {
    "sku": "d58a2ece-4387-41d0-bacb-c4b7935f8405",
    "selectedQtyOptions": [],
    ...
},
{
    "sku": "b8ea355d-7acc-455b-a55c-027b0e5c73cd",
    "selectedQtyOptions": [],
    ...
},
...
]

To achieve this, I used an AngularJS controller and a loop to group the data in sets of four under the screen attribute:

mainApp.controller('MultiCarouselController', function($scope, $http) {

$scope.products = [];
$scope.Math = Math;
$http.get("/get_broad_category_products/?BroadCategory=BroadCategory3")
        .success(function (response) {
            $scope.products = response;
            var iteration = Math.ceil($scope.products.length/4);
            var carouselJson = [];
            for(var index = 0; index < iteration; index++){ 
               var temp = [];
               for (var i = (index*4) ; i < (4*(index+1)) ; i++){
                    temp = temp.concat($scope.products[i])  
                }
                var jsTemp = { "screen": [] };              
                carouselJson.push(jsTemp.screen.push(temp));  
            }
            console.log(carouselJson);
     }).error(function(){
            console.log('An error occurred.');
     });

 });

This code successfully groups the data into sets of four under the screen property. Hopefully, this explanation helps clarify the process!

Answer №1

I have limited experience with angular and its handling of JSON is not something I am particularly fond of.

JSON is essentially a serialized object, making it easy to mix and match data as long as precautions are taken.

Consider two JSON files: JSON1 contains a list of products, each with a unique ID. JSON2 contains amendments to JSON1 that include specific names like "extraImages", "newItems", "updates", and "newData". Simply concatenating the files won't work since they are not arrays, and concatenating JSON strings directly does not work either.

To properly join the two objects, one must have prior knowledge of the data structures and understand the semantic meaning of each item in both files.

The two JSON files in string form are:

// JavaScript objects for JSON1 and JSON2
var JSON1 = `{
    // JSON content for items...
}`;
var JSON2 = `{
    // JSON content for extras...
}`

Working with JSON in string form can be challenging due to difficulty in searching and retrieving data. JavaScript provides a built-in object called JSON for handling JSON data.

The JSON object includes methods such as JSON.stringify(Obj) and JSON.parse(String).

  1. JSON.stringify converts basic JS data types into a JSON string.
  2. JSON.parse converts a JSON string back into a JS Object or Array.

First, convert both JSON strings to objects:

// Convert JSON strings to objects
var items = JSON.parse(JSON1);
var extras = JSON.parse(JSON2); 

Now that we have two plain JS objects, we can manipulate and combine them as needed.

For example, when dealing with extra images that are represented as an array, one needs to iterate through each item in the array and locate the corresponding product by ID.

// Example code for adding extra images to products
if(extras.extraImages !== undefined){ 
     // Iterate over each extra image item
     extras.extraImages.forEach(function(item){
         var arrayOfImages;
         if(item.images !== undefined && typeof item.images === "array"){
               arrayOfImages = item.images;
         }
         // Logic to find and append images to existing products...
     });
  } 
  // Similar logic required for other features such as updates, new items, etc.

By carefully following the semantics of the data structures and understanding the relationships between different elements, one can successfully merge two JSON objects together. Once the necessary modifications are made, the updated object can be converted back to a JSON string using JSON.stringify.

This approach provides a solid foundation for handling JSON data effectively without relying on Angular's abstraction layer. It may require more effort, but it ensures a deeper understanding of the underlying mechanisms.

Answer №2

It seems like you're looking to add a new property to each element within the temp array. One way to achieve this is by creating a new object using your $scope.products[i].

for(var index = 0; index < iteratation; index++){ // Creating a kind of 2D matrix with [0,1],[0,2],[1,1],[1,2]
   var temp = [];
   for (var i = (index*4) ; i < (4*(index+1)) ; i++){
      var destObj = $scope.products[i];
      destObj.screen = 'xx' // Your value assignment goes here.
      temp = temp.concat(destObj)  // Grouping 4 JSON objects together
   }
carouselJson.push(temp);
 }

I hope this explanation is helpful.

Answer №3

this source really assisted me

JavaScript Array Push with key value pair

my loop now looks like this:

var carouselJson = [];
for(var index = 0; index < iteratation; index++){ // representing a 2D matrix as [0,1],[0,2],[1,1],[1,2]
      var temp = [];
      var screen = ['screen'];
      var obj = {};
      for (var i = (index*4) ; i < (4*(index+1)) ; i++){
          temp = temp.concat($scope.products[i]);  // combining 4 JSON objects as a group
         }
      obj[screen]=temp;
      carouselJson.push(obj);  // adding the group to new JSON array
     }
   $scope.mCarousels = carouselJson;

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

Tips for optimizing character count for mobile web pages with varying screen sizes and font settings

As I embark on developing an eBook mobile app, I am faced with various considerations such as screen size, font size, and determining the number of paragraphs to include on a single page based on the current screen and font settings. My aim is to adjust t ...

Make the navigation bar stay at the top of the page when scrolling past another element with a top position of 100vh

Trying to explain a unique concept here. I want a nav bar fixed in the position of top:100vh, so that as I scroll down and reach the next section, the navbar sticks at the top rather than staying stuck at the beginning with position:fixed top:0. The aim is ...

Is there a way to substitute one substring with another substring within the values of an array's objects using Javascript?

var temp = [ { text:'some text and then % sign and then, again % sign', link: 'another text with %', }, ]; I need to modify the temp array of objects to replace all occurrences of % with \%. How can this be achieved? ...

Selecting Elements with JQuery

Hey there, I'm a beginner and I'm facing an issue with selecting an element within my navigation list <ul class="subnav"> <li><a href="#">Link 1</a><span class="sub">Description 1</span></li> <li>& ...

Start progress bars on several divs that share a common class

I'm attempting to utilize the ProgressBar.js Plugin on multiple div elements that share the same class form-progress This is my HTML code: <div class="form-progress"></div> And here is the corresponding JavaScript code: var form_pr ...

Error encountered in Node/Express application: EJS partials used with Angular, causing Uncaught ReferenceError: angular is not defined

I seem to be missing something important here as I attempt to incorporate ejs partials into a single-page Angular app. Every time I try, I encounter an Uncaught ReferenceError: angular is not defined in my partial. It seems like using ejs partials instead ...

React - error caused by an invalid hook call. Uncaught Error: React encountered a minified error with code #

My goal is to incorporate the micro-frontend concept by implementing various react apps. Container Header Dashboard All three are separate applications. I intend to utilize the Header and Dashboard apps within the Container app. For the Header app, it& ...

Add a new variable to the data in a jQuery ajax request for each request with any updates

I've encountered an issue with the code below, which is meant to add additional data to any ajax request made by my app. It works fine when the page first loads, but because my application is single-page and ajax-based, I need the updated variable val ...

ReactJS | Display or Conceal an Array of Objects depending on a specified condition

The Challenge: I am currently working on a task that involves hiding/showing react elements dynamically based on a property of the constructed Object. To be more specific, let's consider the Array of Objects below: const Apps = [ {name: App1, permi ...

Is there a way to substitute user ID with the username in JSON using Django?

I'm currently developing a basic chat feature using ajax, but I am encountering an issue with JSON. Instead of using id, I actually need to utilize the username. The structure of my JSON data is as follows: [{"pk": 41, "model": "chat.post", "fields" ...

Enhance Canvas when React State Changes

I am currently working on integrating a canvas into my React project. The main goal is to overlay styled text (with custom font color, style, and size) on an image. I've set up a basic form to input the styling attributes and the desired text. Whenev ...

Choosing the entire contents of a webpage using jQuery

Is there a way to use jQuery to select all the content on a webpage and copy it to the clipboard for use in another WYSIWYG editor? Here's the scenario: $("#SelectAll").click(function(){ //CODE TO SELECT ALL THE CONTENTS OF THE CURRENT PAGE /* PS: $ ...

Accessing one controller from another module in AngularJS using TypeScript is a common challenge that many developers face. In this article, we

// inside engagement.component.ts: class EngagementMembersController { alphabetic: Array<string> = 'abcdefghijklmnopqrstuvwxyz'.split(''); constructor() {} export const EngagementSetupMember: IComponentOptions ...

In my app.post request in node.js and express, the body object is nowhere to be found

Having an issue with node.js and express, trying to fetch data from a post request originating from an HTML file. However, when I log the request, the req.body object appears empty. I've added a console.log(req.body) at the beginning of my app.post(" ...

Understanding Node.JS: A Dive into Key Concepts

Forgive my lack of knowledge, but I'm really trying to grasp the differences between Node.js and Backbone.js. I believe I'm getting there, but could someone confirm this or guide me in the right direction? Node.js is a platform that can handle H ...

What is the best way to invoke a Servlet from within a d3.json() function

Currently, I am using d3 to create charts with nodes and links connecting them. In order to retrieve the data, I have used a json file named link.json and accessed it using the following code: d3.json("link.json", function(error, graph) {} Although this ...

Exploring Substrings in jQuery/JavaScript

Issue Can anyone help me with locating a specific set of words within a string (gval in this scenario) that defines the specific wordset? if (gval.indexOf("define") > -1){ console.log("Hey! gval has Define"); } var gval = input.val().trim().toLowe ...

The angular ui-router logout state fails to redirect to the login page unless the page is refreshed

After clicking on the logout link, I want to trigger the logout method of the AuthService to clear cookie data and then redirect the user to the login page. However, this process doesn't seem to be working as expected. The page stays on the /logout p ...

The error occurred at line 12 in the app.js file, where it is unable to access properties of an undefined object, specifically the 'className' property. This occurred within an anonymous function in an HTMLDivElement

I am facing an issue with my website where I have buttons on the right side. I want to use JavaScript to change the style of the button when it is clicked. When the page loads, the home button should have a background-color: green. However, when another bu ...

"Implementing a method to return a View along with a JSON response

Is there a way to return the View("controller", model) with JSON result while avoiding errors? I tried the following code snippet but encountered an error. if (thereserror == true) { return Json(new { view = RenderRazor ...