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

Sending data from a JavaScript variable to PHP within the same page

I've been attempting to transfer a JavaScript variable to PHP within the same page without success. I have tried different codes but none seem to be working as expected. Here is the current code snippet: function init(e){ $('#DeleteDaily' ...

getStaticProps will not return any data

I'm experiencing an issue with my getStaticProps where only one of the two db queries is returning correct data while the other returns null. What could be causing this problem? const Dash = (props) => { const config = props.config; useEffect(() ...

Showing undefined or null values in React and JavaScript

My goal is to format undefined or null values by italicizing them. If the value is an empty string, it should be displayed as is. If it has a value, that value should also be displayed as is. However, I am encountering an issue where null or undefined val ...

What is the best way to incorporate a for loop in order to create animations with anime.js?

I am currently working on implementing a for loop to create a page loader using JQuery along with the animation framework anime.js var testimonialElements = $(".loader-animation"); for(var i=0; i < Elements.length; i++){ var element = ...

Interactive Range Slider for Scrolling Through Div Content

I am currently facing an issue where I want to implement a HTML range slider for controlling the horizontal scrolling of a div located below. This functionality is similar to that of a scroll bar, but it will be positioned away from the scrollable content ...

What is the best way to change the number 123456789 to look like 123***789 using either typescript or

Is there a way to convert this scenario? I am working on a project where the userID needs to be displayed in a specific format. The first 3 characters/numbers and last 3 characters/numbers should be visible, while the middle part should be replaced with ...

Using Codeception's selenium module to wait for JavaScript and Ajax requests to

I am currently facing an issue where I need to wait for an ajax call to finish loading before moving on to the next step. I have tried using the waitForJS function, but I am struggling with building the JavaScript condition. I have experimented with diffe ...

Error thrown: SyntaxError - Forbidden break statement in AJAX code execution

Trying to exit a loop nested within a statement has been a challenge. Despite researching similar questions on stackoverflow, I have not found a solution that works. Below is the current code in question: for (var i = 0; (i < 10); i++) { ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

Angular updates location, but browser redirects to incorrect page

I want my application to redirect non-logged in users to a login page. Following advice from a popular source, the app listens for routeChangeStart events like this: $rootScope.$on("$routeChangeStart", function(event, next, current) { if ($rootScope.c ...

Having trouble retrieving the API URL id from a different API data source

For a small React project I was working on, I encountered a scenario where I needed to utilize an ID from one API call in subsequent API calls. Although I had access to the data from the initial call, I struggled with incorporating it into the second call. ...

The module named "jquery" has not been loaded in this context: _. Please use require() to load it

As I work on migrating my Javascript files to Typescript, I encountered an issue when trying to use the transpiled javascript file in an HTML page. The error message I received is as follows: https://requirejs.org/docs/errors.html#notloaded at makeError (r ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

Is there a way to automatically fetch all pages from a REST API request without having to explicitly state the page number each time?

When working with a paginated API to fetch data and convert it into .JSON format, I am looking for a way to retrieve all the pages in the response without explicitly specifying page numbers in the URL. The API allows inputs for page number and results per ...

The accordion seems to be stuck in the open position

Working on a website, I encountered a frustrating bug with an accordion feature. When clicking on the arrow, the accordion opens and closes smoothly. However, when attempting to close it by clicking on the title, the accordion bounces instead of closing p ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

Tips for Transferring Values Between Multiple Dropdown Menus with jQuery

Hello there, can anyone guide me on how to transfer selected items from one multiple combo box to another multi-combo box? I would really appreciate it if someone could provide an example for this scenario. <HTML> <HEAD> <TITLE></T ...

Error: Attempting to insert or update the "tokens" table violates the foreign key constraint "tokens_userId_fkey" in Sequelize

I am facing an issue that I can't seem to resolve, as I keep encountering an error related to a constraint violation. The tables involved in this problem are Token and User, which are linked through the userId column. The error occurs when I try to cr ...

Display a variety of HTML pages using the md-tab component

I'm currently learning about angular material and I have a question regarding how to display different HTML files for each md-tab. For instance, I want to set up 3 tabs: the first one should show catalog.html, the second should display manage.html, an ...

Node js Express js token authentication: unraveling the implementation complexities

After extensive research on authentication methods for nodejs and express js, I find myself at a crossroads. So far, the most helpful tutorial I've found on sessions is this one. I am working with the mean stack and my main goal is to provide users ...