Creating a clone of JSON for use as a template

I am working with a json template that I fill with product data. Here is an example of the json structure:

// product template  
$scope.productAttributes = {
        "Code": null,
        'Attributes':
        {}
    };

When a user inputs product details through a UI and triggers the loadPrices() function, I update the productAttributes like this...

    var loadPrices = function () {
    $scope.entity = {// retrieve form variables};
        $scope.productAttributes.Code = $scope.productID.toUpperCase();
        $scope.productAttributes.Attributes = $scope.entity;
        $scope.productAttributes.Attributes.Term = $scope.productAttributesObj.Term;
        $scope.productAttributes.Attributes.Quantity = 1;          
    };

This is the resulting productAttributes object...

{

"Code": "CON7",    
"Attributes": {        
    "Postcode": "n44er",        
    "rSize": 1000,        
    "Bandwidth": 10,        
    "Term": "36",        
    "Quantity": 1    
}
}

My issue is that every time I call loadPrices, the productAttributes gets overwritten instead of adding new data. I want to achieve a structure like this...

{

"Code": "CON7",    
"Attributes": {        
    "Postcode": "n44er",        
    "Size": 1000,        
    "Bandwidth": 10,        
    "Term": "36",        
    "Quantity": 1    
},
"Code": "CON34",    
"Attributes": {        
    "Postcode": "nww45",        
    "Size": 10,        
    "Bandwidth": 10,        
    "Term": "36",        
    "Quantity": 1    
},
"Code": "CON89",    
"Attributes": {        
    "Postcode": "sw23ed",        
    "Size": 101,        
    "Bandwidth": 101  
}
}

Any suggestions on how I can accomplish this? Any advice would be greatly appreciated.

Additionally, I would like to include an ID field in each "Attributes" object (e.g., "ID": "9e5670fa-2fd7-4858-a667-c99cb5baf0f9"). Is it possible to generate GUIDs using JavaScript or Angular? Thank you!

Answer №1

To convert the variable into an array, simply initialize an empty array and then push objects into it.

$scope.productAttributes = [];

var loadPrices = function () {
  var item = {
    code: $scope.productID.toUpperCase();
    attributes: {
      term: $scope.productAttributesObj.Term,
      quantity: 1
    }
  }

  $scope.productAttributs.push(item);       
};

The structure of your 'item' object can be customized based on your requirements. By pushing these items into the array, you'll achieve the desired outcome.

Answer №2

Give this a shot:

const fetchPrices = () => {
    $scope.data = {/* gathers data from a form*/};
    let myData = {};
    myData.Code = $scope.productID.toUpperCase();
    myData.Attributes = $scope.data;
    myData.Attributes.Term = $scope.productAttributesObj.Term;
    myData.Attributes.Quantity = 1;         

    $scope.productAttributes.push(myData);
};

And make sure to initialize $scope.productAttributes as an Array

$scope.productAttributes = [];

By the way, here's more on manipulating JSON: Manipulating JSON Data with JQuery

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

Exploring the possibilities of integrating jQuery into Firefox extensions

Can someone provide guidance on effectively implementing jQuery within a Firefox extension? My research has not yielded any up-to-date methods that address the latest version of jQuery, and I am aware that directly including it via script tag may lead to c ...

I noticed that while my shareService is effectively sending values in Angular 2, I encounter an issue where my other components are displaying default values instead

I'm in the process of developing an application using angular 2. I have a UserService that sends a value to other components indicating whether a user is logged in or not, and it's working correctly in terms of data transmission. The issue I&apos ...

Leveraging the arguments object within function declarations

Could someone explain why the foo function functions properly? function foo (x,y) { return arguments.length; } However, when I call the boo function with arguments, it returns an error saying undefined is not a function. function boo (c,d) { return ...

Updating padding through local storage does not function as intended

I recently added two buttons to my website for adjusting the padding. While they are functional, I find myself manually setting the padding for nav, main, and footer in the CSS. Here is the snippet of the code: main { padding: 20px 25%; } footer { ...

Issues with retrieving $_POST values from a select form in PHP

When the button is clicked, I am sending a AJAX request to my PHP page using POST method with the selected data from a SELECT element. However, I am facing an issue where my PHP IF statements are not evaluating as true. It always defaults to the ELSE condi ...

Which approach is more impactful: consistently sending an ajax request or breaking down the result within a function?

My JSON data consists of news entries with titles, text, and dates. Here is an example: { "news": [ {"title": "some title #1","text": "text","date": "27.12.15 23:45"}, {"title": "some title #2","text": "text","date": "26.12.15 22:35"}, ... ...

When registering the onHardwareBackButton event in Ionic, the back button continues to successfully navigate to the previous page

I recently started working with Ionic and encountered an issue with the onHardwareBackButton event. The event is functioning properly and directing me to the register function, but even after going to the register function, it still navigates back to the p ...

Issue with the transmission of FormData and string data to PHP

Struggling to properly handle sending file data and string data together through ajax to PHP. Having trouble retrieving the correct string data from $_POST[] in PHP, resulting in only receiving the initial alphabet of a string instead of the specific produ ...

Retrieving the Selector Value during a Change Event

Is there a way to retrieve the selector value in a change event? I attempted this approach: $("#frek_menonton_tv :input").change(function(){ $(this).selector; }); However, it only returns an empty string. Desired outcome: frek_menonton ...

"Encountered npm error: JSON input ended unexpectedly" while trying to install express-mysql-session"

I'm currently developing a nodejs project that uses passportjs for user authentication and mysql as the database. I'm now looking to incorporate session storage by utilizing the ""express-mysql-session" package. However, when attemptin ...

Can the server-side manipulate the browser's address bar?

Picture this scenario: a public display showcasing a browser viewing a web page. Can you send a GET or POST request from a mobile device to an HTTP server, causing an AJAX/pubsub/websocket JavaScript function to alter the displayed page on the screen? Per ...

Do we need to employ strict mode when utilizing specific ES6 functions in Node.js?

There has been a debate circulating at my workplace regarding whether or not it is necessary to include 'use strict' when using ES6 in Node.js without Babel. Some argue that certain ES6 methods may not function correctly without it, but I haven&a ...

Modify section background color for every iteration in an image carousel

Is it possible to dynamically change the background color of the cd-hero section each time a new image is loaded in a simple slider on the home page? Can this be achieved by storing predefined colors in an array so that different images trigger different b ...

The CORS policy is preventing the AJAX request from functioning properly on localhost

Recently, I have been working on an Angular application that requires interaction with an API. To test it out, I set up an API on my localhost and made a request using AJAX. However, I encountered the dreaded CORS error. Despite trying various solutions fo ...

I am facing an issue where the HTML button is not properly interacting with the JavaScript function

function idk() { let cypher = {A:"G",B:"L",C:"Z",D:"E",E:"Y",F:"R",G:"D",H:"N",I:"K",J:"W",K:"J",L:"B",M:"Q",N:"F",O:"S",P:"C",Q:"V",R:"X",S:"I",T:"O",U:"M",V:"T",W:"A",X:"U",Y:"H",Z:"P"}; var answer = prompt('What cypher are you going to use 1 - 26& ...

`AngularJS Voice Recognition Solutions`

In my quest to implement voice recognition in an AngularJS application I'm developing for Android and Electron, I've encountered some challenges. While I've already discovered a suitable solution for Android using ng-speech-recognition, fin ...

Does Angular's compile function operate asynchronously?

In my service, I use $compile to compile the template. The JavaScript functions are executed one after another, but in order to retrieve the final HTML content, I have to place html() within a timeout callback. Otherwise, the template includes {{ placeho ...

Auto-fit HTML Webpage Resizer Simplified

Just finished my very first jQuery project, a simple full-width slider. I've been focusing on HTML & CSS and currently working with C#. The problem is that I don't want the page to be scrollable; I want it to autofit to the webpage. Imagine ope ...

Emulating Data in Angular 2 Using Configuration Similar to Ember Mirage

Is there a way to mock data through configuration in Angular 2 similar to how it's done in Ember Mirage? I'm aware that I can create my own solution using Dependency Injection and MockBackend to intercept HTTP calls and provide dummy data. Howeve ...

Tips for effectively utilizing "Session" in jQuery

Are there any comparable features in jQuery to Session["Param"] in C#? How can I implement it? I've looked up "sessionStorage" in jQuery, but I'm having trouble grasping it. ...