What is the proper way to include an attribute to every individual object within an array?

Here is the structure of my array:

"taxDetails": [
{
  "taxType": "Flat Service Charge",
  "taxAmount": 0
},
{
  "taxTypeId": "1",
  "taxType": "Service Tax",
  "validFrm": "2016-01-18",
  "validTo": "2020-02-27",
  "taxPrctgSbt": 200,
  "taxPrctg": 14.5,
  "taxAmount": 300,
  "remarks": "test"
},
{
  "taxTypeId": "2",
  "taxType": "VAT",
  "validFrm": "2016-01-18",
  "validTo": "2020-02-29",
  "taxPrctgSbt": 300,
  "taxPrctg": 12.5,
  "taxAmount": 400,
  "remarks": "rest"
},
{
  "taxTypeId": "3",
  "taxType": "Swatch Bharath Cess",
  "validFrm": "2016-01-18",
  "validTo": "2020-03-31",
  "taxPrctgSbt": 400,
  "taxPrctg": 1,
  "taxAmount": 500,
  "remarks": "fest"
},
{
  "taxTypeId": "5",
  "taxType": "Swatch Bharath Cess",
  "validFrm": "2016-01-18",
  "validTo": "2020-03-31",
  "taxPrctgSbt": 400,
  "taxPrctg": 1,
  "taxAmount": 500,
  "remarks": "fest"
},
{
  "taxTypeId": "6",
  "taxType": "Percent Service Char",
  "validFrm": "2016-01-18",
  "validTo": "2020-08-01",
  "taxPrctgSbt": 200,
  "taxPrctg": 10,
  "taxAmount": 200,
  "remarks": "zest"
},
{
  "taxTypeId": "7",
  "taxType": "Percent Service Char",
  "validFrm": "2016-01-18",
  "validTo": "2020-08-01",
  "taxPrctgSbt": 300,
  "taxPrctg": 15,
  "taxAmount": 200,
  "remarks": "zest"
}
]

Below is the code snippet:

$scope.paymentForm.taxDetails = [];
//$scope.taxDetails =  [];
var flat= {"flat" : true};
$scope.taxList = function () {
    $http.get('http://192.168.0.113:8080/feasthunt/registration/getTaxDetails?restUniqCode='+uniqueCode)
    .success(function (response) {

        $scope.paymentForm.taxDetails = response;

        for(var i=0; i< $scope.paymentForm.taxDetails.length; i++){
             $scope.paymentForm.taxDetails[i].push( flat );
                }
    })
    .error(function (data, status, header, config) {
        //alert('error');
    });
};
$scope.taxList();

The goal is to add another object in every element array to achieve this final format:

"taxDetails": [
{
  "taxType": "Flat Service Charge",
  "taxAmount": 0,
  "flat": true
},
{
  "taxTypeId": "1",
  "taxType": "Service Tax",
  "validFrm": "2016-01-18",
  "validTo": "2020-02-27",
  "taxPrctgSbt": 200,
  "taxPrctg": 14.5,
  "taxAmount": 300,
  "remarks": "test",
  "flat": true
},
{
  "taxTypeId": "2",
  "taxType": "VAT",
  "validFrm": "2016-01-18",
  "validTo": "2020-02-29",
  "taxPrctgSbt": 300,
  "taxPrctg": 12.5,
  "taxAmount": 400,
  "remarks": "rest",
  "flat": true
},
{
  "taxTypeId": "3",
  "taxType": "Swatch Bharath Cess",
  "validFrm": "2016-01-18",
  "validTo": "2020-03-31",
  "taxPrctgSbt": 400,
  "taxPrctg": 1,
  "taxAmount": 500,
  "remarks": "fest",
  "flat": true
},
{
  "taxTypeId": "5",
  "taxType": "Swatch Bharath Cess",
  "validFrm": "2016-01-18",
  "validTo": "2020-03-31",
  "taxPrctgSbt": 400,
  "taxPrctg": 1,
  "taxAmount": 500,
  "remarks": "fest",
  "flat": true
},
{
  "taxTypeId": "6",
  "taxType": "Percent Service Char",
  "validFrm": "2016-01-18",
  "validTo": "2020-08-01",
  "taxPrctgSbt": 200,
  "taxPrctg": 10,
  "taxAmount": 200,
  "remarks": "zest",
  "flat": true
},
{
  "taxTypeId": "7",
  "taxType": "Percent Service Char",
  "validFrm": "2016-01-18",
  "validTo": "2020-08-01",
  "taxPrctgSbt": 300,
  "taxPrctg": 15,
  "taxAmount": 200,
  "remarks": "zest",
  "flat": true
}
]

Answer №1

It seems like you are aiming to assign the attribute flat=true to every element in an array. Here is a possible code snippet that might achieve this:

for(let index=0; index < $scope.paymentForm.taxDetails.length; index++){
  $scope.paymentForm.taxDetails[index].flat = true;
}

Answer №2

Instead of trying to push the new property to an object as if it were an array, you should set the new property directly.

Replace:

for(var i=0; i< $scope.paymentForm.taxDetails.length; i++){
    $scope.paymentForm.taxDetails[i].push( flat );
}

With:

for(var i=0; i< $scope.paymentForm.taxDetails.length; i++){
    $scope.paymentForm.taxDetails[i]["flat"] = true; //or any other value you prefer
}

You could also opt for a for-in loop to simplify the code:

for(var i in $scope.paymentForm.taxDetails)
    $scope.paymentForm.taxDetails[i]["flat"] = true;

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

Global variables in AngularJS that are asynchronous

My challenge lies in using AngularJS to create several global objects accessible by any controller within the application. One crucial object I require is a user object containing the user's ID and other essential properties retrieved from the databa ...

Child component in Angular fails to detect input changes

Hey there! I'm currently utilizing parent-child communication in my Angular project. In the parent component, I have an array that represents graph data. If you'd like to check out a demo of what I'm working on, feel free to click here. The ...

How to Find and Count Duplicate Values in an Array using AngularJS

My form consists of 5 questions, each with 3 different answers to choose from. For example: q1. What is your favorite color? Radio button-1: blue Radio button-2: red Radio button-3: grey While most questions offer the same values (blue, red, grey), I am ...

The renderToString function in Material UI's sx property doesn't seem to have

Every time I apply sx to a component that is rendered as a string and then displayed using dangerouslySetInnerHtml, the styles within the sx prop do not work. Here is an example showcasing the issue: Codesandbox: https://codesandbox.io/p/sandbox/wonderfu ...

Leverage the sync function within the await .then("sync") method in JavaScript

If a synchronous function is called within the .then part of an asynchronous await .then, such as: await asyncFunc(...) .then(res => sendMSG(res)) .catch(err => next(err)); function sendMSG(res){ xyz } The sync function sendMSG i ...

Send a POST form from my website to another website and retrieve the data from the remote server

My website, example.com, includes a web HTML form that leads to another site where the results are currently displayed. I want to retrieve these results from the other website using PHP or some other method and showcase them on my own site. However, the fo ...

Send a file from a form using Gatsby to getform.io using the axios library

I am facing an issue with my getform.io form where the file is not getting uploaded properly. The file appears as [] and the files tab remains empty. Upon checking the network tab, I noticed that my request payload includes {email: "[email protec ...

Performing an HTTP GET request to an endpoint within a RESTful API

I am looking to integrate a feature in my web application that displays the list of online users on my website. To achieve this, I need to make an HTTP GET request to the URL which returns the user data in JSON format. The returned JSON data contains var ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

What is the best way to automatically log out a user when a different user logs in on the same browser?

Currently, I am encountering an issue where there are two separate dashboards for different types of users - one for admin and the other for a merchant. The problem arises when an admin logs in on one tab and then a merchant logs in on another tab in the s ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

Issue with AngularJS in Internet Explorer 7: "querySelector" property or method not supported by object

Incorporating angularjs into an existing asp.net project has presented a challenge due to the project's dependency on IE 7 compatibility mode. Upon running the project, an error from the angularjs file was encountered: Object doesn't support pro ...

I'm not entirely sure why I keep getting the error message stating "Cannot read property 'innerHTML' of null"

Having an issue with my JavaScript code where I am trying to insert a new table row into the HTML but keep getting an error message that says "Uncaught TypeError: Cannot read property 'innerHTML' of null" <!DOCTYPE html> <html lang=" ...

Error encountered when attempting to export a TypeScript class from an AngularJS module

In my application using Angular and TypeScript, I have encountered a scenario where I want to inherit a class from one module into another file: generics.ts: module app.generics{ export class BaseClass{ someMethod(): void{ alert(" ...

Graph columns failing to display on Chart.js bar chart

I'm currently facing a challenge while trying to create a bar chart using HTML and JavaScript. Unfortunately, the bars are not showing up for some reason. I have included the code snippet below along with an imagehttps://i.stack.imgur.com/4H7ol.png. ...

Generating Tree Structure Object Automatically from Collection using Keys

I am looking to automatically generate a complex Tree structure from a set of objects, with the levels of the tree determined by a list of keys. For example, my collection could consist of items like [{a_id: '1', a_name: '1-name', b_id ...

Material-inspired Design Device Compatible DIV slide with JS, JQuery, and CSS

My goal is to achieve something similar to this: Desired Live Website I am looking for a feature where clicking on the div will slide in content from the right, load an external page inside it, and close when prompted. The slider div should be device c ...

Preserving the top line or heading while cutting through a table

In my HTML, I have a table with the following structure: <table id="table"> <tr> <td>ID</td> <td>Place</td> <td>Population</td> </t ...

Loop through an array of buttons using an event listener

My HTML and Javascript code currently have the functionality to show/hide a row of 3 images upon button click. However, I need this feature to work for two additional rows similar to this one. I believe it involves looping through an array of buttons, but ...

Removing a specific row in a database table and sending a boolean indicator to an API, all while keeping the original object intact

I'm currently working on a spa project using AngularJS and integrating an api with mvvm in C#. One issue I am facing is that when I click the delete button, it deletes the line but I only want to change a boolean flag to true on the server side while ...