Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array.

Here is a snippet of the array structure that I receive:

[
  {
    "ErrorType": "Errors",
    "Explanations": [
      {
        "Explanation": "Price Missing",
        "Locations": [
          25,
          45
        ]
      },
      {
        "Explanation": "Unit of measurement not valid",
        "Locations": [
          25,
          301,
          302
        ]
      }
    ]
  },
  {
    "ErrorType": "Warnings",
    "Explanations": [
      {
        Blablabla,
        Ithinkthere's already much here
      }
    ]
  }
]

After fetching the data, I store it in a JavaScript array like so:

$scope.CorrectionDatas = ResponseFromApi;

My goal is to enhance this array by adding a new property for each 'ErrorType', resulting in the following structure:

[
  {
    "ErrorType": "Errors",
    "Explanations": [
      {
        "Explanation": "Price Missing",
        "Locations": [
          25,
          45
        ]
      },
      {
        "Explanation": "Unit of measurement not valid",
        "Locations": [
          25,
          301,
          302
        ]
      }
    ],
    "show": true
  },
  {
    "ErrorType": "Warnings",
    "Explanations": [
      {
        Blablabla,
        Ithinkthere's already much here 
      }
     ],
    "show":true
  }
]

I attempted to achieve this by using the following approach:

$scope.CorrectionDatas.forEach(function (error) {
    error.push({ show: true });
});

However, upon running my code, I encountered the following debugger error:

Error: error.push is not a function 
$scope.getErrors/</<@http://localhost:1771/dependencies/local/js/Correction/CorrectionCtrl.js:26

Answer №1

Every mistake is treated as an individual object, making it unnecessary to use the push function. To correct this, modify the code as follows:

        $scope.CorrectionDatas.forEach(function(mistake) {
            mistake.display = true;
        });

Answer №2

Here's a new approach to solve this issue:

$scope.CorrectionDatas.forEach((error) => {
     error["display"] = true;
});

Answer №3

It appears that the issue you are facing stems from error being an object instead of an array. You can verify this by checking the output of typeof error. In such cases, it is necessary to explicitly set the show property of the object. Here's how you can achieve that:

$scope.CorrectionDatas.forEach(function (error){
    error['show'] = true; // or error.show = 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

What is the best way to trigger a modal on Bootstrap using a JavaScript/jQuery function?

I encountered an issue while attempting to call a bootstrap modal using a simple button or link, which may be due to a conflict with my select2 plugin (although I am uncertain). I tried appending the button to the select2 dropdown but it doesn't seem ...

executing npm tasks concurrently

Trying to demonstrate running npm tasks in parallel is my current task. I should be able to achieve this using "&" for parallel and "&&" for series. { "name": "npm", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "co ...

Exploring the topic of AngularJS unit testing and working with httpBackend timeouts

I have experience in the testing world, particularly with TDD using tools like mocha, sinon, chai, and nodejs. Recently, I've been finding AngularJS testing a bit challenging to grasp and implement. Currently, I am trying to test the simplest method ...

Utilizing ng-repeat and ng-if to display dynamic data fetched from the server

I have social media icons with a like button that turns red only if item.like== 1, or remains white if item.userid==0. I am updating this dynamically and need to call the function profileData() again when a user clicks the like button. However, every time ...

Retrieving data from Immediately Invoked Function Expressions

I've been working with a closure that looks like this: var Container = (function () { var variable; var changeVariable = function () { variable = 5; }; return { variable: variable, changeVariable: changeVariable }; ...

Encountering issues with the setValue function in Nightwatch

Currently, I am in the process of setting up a new Nightwatch project to automate a basic Google search page. The assertion for searchbox present on page is successful, but I am facing difficulties performing any mouse or keyboard actions on the elements ( ...

Definition file for Typescript Angular 1.5 component

Encountering a problem with typescript and angular 1.5 - when building, an error pops up saying error TS2339: Property 'component' does not exist on type 'IModule'.. Could it be that I overlooked a definition file containing this proper ...

Ensure to first close the existing global connection before attempting to establish a new one in your Node.js Post WebApi application

Currently, I am in the process of creating a small post WebAPI using node.js to collect user data such as names and numbers. However, when I have an excessive number of users accessing this web API, I encounter the following error message: "node.js Global ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...

Utilize array collections across various pages for increased efficiency

Currently, I am working with two pages - page1.php and page2.php. Each page has its own controller that handles specific functions. However, there are tabs within both pages that share the same functionality of obtaining a promise from a factory within the ...

Retrieving data from a jSONobject

I have been working on a web service and encountered an issue with retrieving values from a JSON object. I created a parser class to handle this but ran into a problem where the main object was returning as null, causing the subsequent code to not work pro ...

What is the best way to run a function within an if statement without duplicating code if the condition is false?

When working with relay mutation code, I find it necessary to reload the store in order for it to sync with the database. This is because if the text being added is the same as previously added text, the relay store throws an error called flattenChildren.. ...

When the VueJS element is rendered on Chrome addon, it suddenly vanishes

I have been using a developer mode addon successfully in Chrome for quite some time. Now, I want to add a button to my Vue-powered page. Here's the code snippet: let isletCtl = document.createElement('div') isletCtl.id ...

Converting JSON into Java POJO objects with a dynamically generated key

I'm currently in the process of converting JSON to JAVA POJO. The JSON string I'm working with is structured as follows: { "api": { "results": 1, "fixtures": [ { "fixture_id": 38480 ...

Ways to stop your Browser from Caching

Developing a Facebook app has been my recent project. One thing that really bothers me is the random occurrences where changes I make to my CSS style sheet or when adding a new Javascript function do not reflect in the browser. This can be very frustrating ...

Encountering an internal/modules/cjs/loader.js:892 error when attempting to install the newest version of node.js on Windows 10

After recently updating my node.js to the latest version using chocolatey, I encountered a problem with my command prompt displaying the following error: internal/modules/cjs/loader.js:892 throw err; ^ Error: Cannot find module 'C:\Users&bso ...

Displaying a div when hovering over it, and keeping it visible until clicked

I want to display a div when hovering over a button. The shown div should be clickable and persistent even if I move the cursor from the button into the shown div. However, it should be hidden when moving out of the entire area. I'm unsure about how ...

Updating a React component upon pressing a button to trigger a re-render

Currently, I am in the process of developing a React component that allows users to input an ID and retrieve relevant information upon submission. The code for this component is structured as follows: export default class IDContainer extends React.Componen ...

Setting up a Celery task from Java: "Unknown message received and deleted. Incorrect destination specified"

I need help with scheduling a Celery task from Java. Here's how I'm sending the task to RabbitMQ: ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.crea ...

Develop a seamless user experience by creating dynamic forms using Jquery, PHP, and

I have been attempting to create a simple contact form using jQuery, AJAX, and PHP without refreshing the page. Everything seems to be working smoothly except for event.preventDefault(); Here are my files: Contact_engine.php <?php $name = $_POST ...