Generating an Angular JSON object on the fly

I currently have a JSON object structured in the following format. Although it's hardcoded at the moment, I'm looking to dynamically generate this JSON by looping through another object.

The second object should be iterated over in order to construct the JSON object with the given structure.

[
{
    name: "test1",
    enable: true,
    unit: 24350,
    unit_price: 1.0368,
    composition: [
        {
            asset: "asset1",
            percentage: 15
        },
        {
            asset: "asset2",
            percentage: 10
        },
        {
            asset: "asset3",
            percentage: 5
        },
        {
            asset: "asset4",
            percentage: 35
        },
        {
            asset: "asset5",
            percentage: 20
        },
        {
            asset: "asset6",
            percentage: 15
        }
    ]
},
{
    name: "test2",
    enable: true,
    unit: 24350,
    unit_price: 1.0368,
    composition: [
        {
            asset: "asset1",
            percentage: 15
        },
        {
            asset: "asset2",
            percentage: 10
        },
        {
            asset: "asset3",
            percentage: 5
        },
        {
            asset: "asset4",
            percentage: 35
        },
        {
            asset: "asset5",
            percentage: 20
        },
        {
            asset: "asset6",
            percentage: 15
        }
    ]
}
]

Thank you in advance for your assistance.

Answer №1

function UserAuthenticator($scope) {
  $scope.users = [{
      "name": "Mike",
      "age": 28,
      "active": true,
      "attributes": [{
        "type": "admin"
      }, {
        "level": 5
      }]
    }, {
      "name": "Sarah",
      "age": 32,
      "active": false,
      "attributes": [{
        "type": "moderator"
      }, {
        "level": 3
      }]
    }

  ];
  $scope.userData = [];
  var tempUserObj = [];
  for (i = 0; i < $scope.users.length; i++) {
    var tempUserObj = {

      "name": $scope.users[i].name,
      "age": $scope.users[i].age,
      "active": $scope.users[i].active,


    };
    tempUserObj.attributes = [];
    tempAttributes = {
      "type": $scope.users[i].attributes[0].type,
      "level": $scope.users[i].attributes[1].level
    };
    tempUserObj.attributes.push(tempAttributes);

    $scope.userData.push(tempUserObj);
  }
  console.log('userData', $scope.userData);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-app ng-controller="UserAuthenticator">
  <table>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Active</th>
      <th>Attributes
        <table>
          <th>type</th>
          <th>level</th>
        </table>
      </th>
    </tr>
    <tr ng-repeat="user in userData">
      <td>{{ user.name }}</td>
      <td>{{ user.age }}</td>
      <td>{{ user.active }}</td>
      <td>{{ user.attributes[0].type}}</td>
      <td>{{ user.attributes[0].level }}</td>
    </tr>
  </table>
</div>

Answer №2

Just stick to using plain Javascript's JSON.parse method.

var info = [
    {
      label: "test1",
      status: true,
      count: 24350,
      price_per_unit: 1.0368,
      breakdown: [
        {
            element: "asset1",
            ratio: 15
        },
        {
            element: "asset2",
            ratio: 10
        },
        {
            element: "asset3",
            ratio: 5
        },
        {
            element: "asset4",
            ratio: 35
        },
        {
            element: "asset5",
            ratio: 20
        },
        {
            element: "asset6",
            ratio: 15
        }
      ]
    },
    {
      label: "test2",
      status: true,
      count: 24350,
      price_per_unit: 1.0368,
      breakdown: [
        {
            element: "asset1",
            ratio: 15
        },
        {
            element: "asset2",
            ratio: 10
        },
        {
            element: "asset3",
            ratio: 5
        },
        {
            element: "asset4",
            ratio: 35
        },
        {
            element: "asset5",
            ratio: 20
        },
        {
            element: "asset6",
            ratio: 15
        }
      ]
    }]

var parsedJson = JSON.parse(info);

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

How to achieve a typewriter effect in React using JavaScript

I've been attempting to incorporate a typewriter effect into my website - at the moment, the animation is functioning but each letter appears twice (e.g. instead of reading "Welcome!" it displays "Wweellccoommee!!"). I suspect this is an asynchronous ...

Increase the item count in React only when the button is initially pressed

Users have the option to join various exercise objects by clicking a button, and the Sidebar component will indicate how many different exercises they have joined. The user's count of exercises should only increase if they haven't already joined ...

Fetching the model or collection

Having recently transitioned from ExtJS to Backbone, I am looking to populate a Backbone collection with data. In ExtJS, I would typically use the .load() method to accomplish this. However, in Backbone's documentation, I notice that there are primari ...

Issue with Material UI styles not applied in component (alert: multiple occurrences of `@material-ui/styles`)

I have developed a standalone React component that utilizes the Material UI (4.8.3) library and have uploaded it to a private NPM package for use across various applications. The standalone component project is functioning properly (tested using Storybook ...

Sharing the port of a local Node.js HTTP server (which is being executed in an Electron environment) with an Angular

Running a RESTful node JS Http server on localhost within an electron app, listening on port 0 to get a random free port. How can I access this randomly assigned port in my Angular code to determine the URL for XHTTP requests? Nodejs restapi server runnin ...

Error with review score in material-ui for react.js

There is an issue with my code where the ratings from different sets are not behaving independently. When a rating in one set is clicked, only the first set of ratings changes, suggesting that there is a connection between all the sets. https://i.sstatic. ...

What is the best way to ensure that the React useEffect hook is triggered only once following a state change

I am brand new to the world of React hooks and I'm facing a specific challenge. Imagine that we have two states, state1 and state2, and we are using the useEffect hook to call asyncFn1 and update state1. My goal now is to wait for a change in state1 ...

Using JavaScript (without jQuery), take away the CSS class from an element

Seeking assistance from experts on the process of removing a class from an element solely using JavaScript. Kindly refrain from suggesting solutions involving jQuery as I am unable to utilize it, and have little knowledge about its functionalities. ...

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Expression enclosed in double quotes within a JavaScript string

Our company has encountered an issue with an FTL that involves a link with JavaScript functionality. The problem arises when the value contains an apostrophe, causing the link to break. To address this, we utilized the js_string method to solve the issue. ...

Verify for any alterations in the code by utilizing the inspect element feature

Currently dealing with a security concern regarding my older Java application. Is there a method available to detect any modifications made to my code (HTML or script) through Developer Tools on the user's end? This would allow me to prevent form subm ...

"Exploring the world of JavaScript through the lens of time

This summer, I have the opportunity to assist a friend with some JavaScript challenges on his website. The main issue seems to revolve around technical difficulties with online form submissions. Unfortunately, there are instances where we struggle to verif ...

Verify the username in the registration form before clicking the Register button

I have a PHP-based website and I want to implement a user registration form with unique usernames. How can I validate the username before submitting the request to the database for registration? ...

Utilizing the native cursor feature in Adobe AIR JavaScript using MouseCursorData

I have been exploring the content of this article: which details how to create a native cursor in AIR without resorting to using a sprite to mimic the functionality. However, my project is based on HTML/JavaScript rather than ActionScript. Here is the c ...

Error 404 occurs when refreshing an Angular http-server page

I am facing an issue with my Angular application where the controller is routed as follows: controllers/favorites.js ... $stateProvider.state('app.favorites' {url: '/favorites'} ...); index.html ... <a ui-sref="app.favorites"> ...

What is the best way to enable a link upon clicking while simultaneously disabling the others using JavaScript?

When I click on a link, I want to handle just that one element. However, when I click on another link, the active class is not being removed from the previous ones. Can anyone offer assistance with this issue? Here's my code: let parentT = document.qu ...

Center the title vertically APEXCHARTS

I created this chart using Apex charts https://i.sstatic.net/j34Wc.png However, I am facing an issue where the 'Chart' title and caption are not properly aligned. The title should align with the graph horizontally, and the caption vertically. ...

Creating a customized date picker design with Material UI

Instead of displaying the date in DD/MM/YYYY format, I would like to show "Today" text. For example, when using a datepicker, the browser may display a date like 20/1/2009. However, I want it to show "Today" instead of that specific date. ...

What is the best way to choose two <li> elements with multiple classes in my WordPress navigation menu?

I am looking for a JavaScript function that will add the class "current_highlight" when an element with the class "activo2" also has the class "active". Here is my HTML code: <div class="navbar-header"> <button type="button " class="navbar-to ...

The creation of numerous DOM elements in D3

I'm currently utilizing the Tableau JS API to develop animated charts with D3.js. Within a Canvas(DOM) element, I am generating the necessary charts using the getUnderlyingData() function. This function is triggered whenever there's a change in f ...