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

Trouble with document updates in MongoDB/Mongoose causing a delay?

I am currently working on updating an object nested in an array in my application. When I test this functionality using Postman, I am experiencing a delay that requires me to make two requests in order to see the updated value. if (taskStatus) { cons ...

Converting JSON data into a table using jQuery, with certain columns hidden from view

I am currently working on developing a mobile app using jQuery Mobile and JSON. I have encountered two separate questions: 1) I have a JSON data set which includes fields such as id, name, surname, point, and mail. In my table that lists this data, I init ...

Is it possible to create tags in Material UI Autocomplete using events other than just pressing the 'Enter' key?

In my current project, I am utilizing the freesolo Autocomplete feature. My specific requirement is to create tags when input text is followed by commas or spaces. Currently, tags are created on the Enter event by Autocomplete, but I am looking for a way t ...

Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code: <html> <head> </head> <body style="text-align:center;" id="body"> <p id="GFG_UP1" style="font-size: 16px;"> </p ...

A guide to testing the mui Modal onClose method

When using material UI (mui), the Modal component includes an onClose property, which triggers a callback when the component requests to be closed. This allows users to close the modal by clicking outside of its area. <Modal open={open} onCl ...

Determining the Similarity of jQuery Selectors' Selected Elements

I'm looking for a way to programmatically identify if two jQuery selectors have chosen the exact same element. My goal is to iterate over multiple divs and exclude one of them. This is what I envision: var $rows, $row, $row_to_exclude; $rows ...

Getting access to props within a child component's mounting phase

It is commonly understood that when the child component is mounted before the parent component, trying to access props in the child component's mounted period will result in null. However, I recently came across a scenario where props were successful ...

Troubleshoot your Vue.js application using Visual Studio Code. Encounter an unidentified breakpoint error

I'm encountering a problem with debugging my Vue.js project using VS Code and Chrome. I followed the official guide on the website Guide, but it's not working for me. The error I keep running into is: unverified breakpoint What am I doing wrong? ...

Leverage the jQuery select2 plugin in conjunction with AngularJS

Currently, I am working on enhancing a Single Page Application (SPA) with AngularJS. I am interested in incorporating the jQuery Select2 plugin into the project. Does anyone have guidance on how to integrate this plugin seamlessly with AngularJS? The dat ...

Is it possible to create floating unordered lists using Bootstrap in HTML?

Is there a way to float text left or maintain list order in the HTML code of my page while using a dense CSS from this bootstrap template? For example, I would like my list to remain organized regardless of how many items are added: However, after adding ...

The Console.log() function displays the current state and value of a promise object within the Q library

Whenever I attempt to print a promise object from Q, the result that I receive is as follows: var Q = require('q'); var defaultPromise = new Q(); console.log('defaultPromise', defaultPromise); defaultPromise { state: 'fulfilled& ...

Leveraging useEffect and useContext during data retrieval

I'm currently in the process of learning how to utilize React's Context API and Hooks while working on a project that involves using fetch(). Although I am able to make the request successfully, I encounter an issue where I can't retrieve t ...

Is your Angular 2 routing failing to work properly after a page refresh or reload when using gulp?

I've recently started learning Angular 2, and I encountered an issue with routing. During the development phase, I ran my application using npm start. However, after migrating to gulp.js, when I run the application by typing gulp, everything works fin ...

Iterate through the JSON data values using a loop and showcase each one by presenting them in individual cards

I'm having trouble determining which type of loop to use in this situation because I am still learning jQuery and JS. On the result page, I have set up cards to separate each piece of data from the JSON file, but I am unsure how to actually display th ...

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

Encountering NPM install gyp errors in VSCode indicating that gyp is searching for Visual Studio

Running npm install on a local project has been quite challenging for me, as I keep encountering errors every time I try. Fortunately, some valuable information I found related to gyp and Python helped me make some progress. However, I'm currently fac ...

Text field suddenly loses focus upon entering a single character

In my current code, I have functions that determine whether to display a TextField or a Select component based on a JSON value being Text or Select. However, I am facing an issue where I can only enter one letter into the TextField before losing focus. Sub ...

Is there a way to improve or simplify this jQuery validation code?

I am implementing client side validation using jQuery to ensure all fields are filled in before proceeding. var passedValidation = new Boolean(true); // Validate Required Fields if ($('#fbsignup input.firstName').val().trim() == '') { ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Tips for providing the URL in JSON using Spring MVC

Every time I try to run my code, I encounter an issue where I cannot access the URL specified in the getJSON function. Below is my controller code: @RequestMapping(value = "branch") @Controller public class BranchController { @Autowired(required = true) ...