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

The lightbox feature seems to be malfunctioning, despite having successfully loaded jQuery

Struggling to activate lightbox on my gallery. Jquery is functioning as verified with an alert() in the documet.ready(). However, lightbox does not seem to be working properly. Only the links are operational. Below is a snippet of my code: <!DOCTYPE ht ...

Is it possible to have setTimeOut() executed after the page has been redirected?

Why is it not possible to duplicate: The question was not addressed in the previous post. I have a link for deletion, which, when clicked, triggers a popup with a button. Upon clicking that button, the page inside the popup redirects to a new internal pag ...

Traverse Through Nested JSON Data and Display it in an HTML Table using Vue

Struggling to find a way to loop through my data, I have JSON data presented like this: [ { "STATUS":"CUTTING INHOUSE", "STID":"1", "CATS":[ { "CAT":"ORIGINALS ", "ARTS":[ { "ARTNO":"GY8252", ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

Guide to building a React site that showcases customized content from users in a visually appealing way

Imagine you're designing a website where users can share their writing, whether it's a blog, a platform like Medium, or even StackOverflow. You want to allow users to format text with bold and italic styles, insert pictures within the text, and m ...

Navigating through an array in JSON using Swift

https://i.sstatic.net/Enm2u.png I have created a structure to decode the data obtained from JSON. https://i.sstatic.net/LZ8FC.png In the main code section, I access the array result and retrieve the title to print it out. The result array contains 14 item ...

Why is the function not being executed despite having the correct syntax?

Hey there! I've developed a function that's supposed to take an array of Student details and display it, but for some reason, it isn't working correctly. Any ideas on what might be causing this issue? Your help is greatly appreciated! fun ...

There was a dependency resolution error encountered when resolving the following: [email protected] 12:15:56 AM: npm ERR! Discovered: [email protected] . The Netlify deploy log is provided below for reference

5:27:42 PM: Installing npm packages using npm version 8.19.3 5:27:44 PM: npm ERR! code ERESOLVE 5:27:44 PM: npm ERR! ERESOLVE could not resolve 5:27:44 PM: npm ERR! 5:27:44 PM: npm ERR! While resolving: [email protected] 5:27:44 PM: npm ERR! Foun ...

Is there a way to retrieve the "name" value from the puppet metadata.json file using shell scripting without using jq?

Due to certain limitations, I am unable to use jq or any other CLI tool. My task is to extract the value of "name" from a JSON file that adheres to the Puppet metadata.json format. The JSON may not be properly formatted with correct indentation, but it wi ...

Download Apple information in JSON data format as a text file

I wrote a script that retrieves Apple data from the Apple Search API and formats it for display on my website. When I try accessing the lookup URL in my browser, it prompts me to download the data as a text file. The script was working fine when I ran it ...

How to locate the index of a specific item or multiple items within a JsonArray?

Can you help me determine which city is closest to Vancouver: Victoria, Washington or Texas? Once I find the shortest distance, how can I identify which destination address this value corresponds to? { "destination_addresses" : [ "Victoria, BC, C ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

encountering a loading issue with angular2-modal in rc1 version

Currently, I am implementing a library called angular2-modal. This library offers various modal options including bootstrap and vex for angular 2. While vex is functioning properly, I encounter an error when switching to bootstrap: responsive-applicati ...

Is there a way to selectively import specific functions from a file in NextJs/React rather than importing the entire file?

Imagine this scenario: we have two files, let's call them File A - export const a = () => {} export const b = () => {} Now, consider importing this into File B - import { a } from 'path' When I tried running npm run analyze, it showe ...

Unable to call Ionic component function using ref in Vue3

I'm attempting to utilize the closeSlidingItems method of the IonList element in order to automatically close the sliding item after clicking a button that appears from behind once the item is slid to the right. My approach involved referencing IonLi ...

Generate a 2D array resembling a grid

I have limited experience with Java and am facing a project with tight deadlines. I need assistance with the following class: public static void getAllDataDB1() // Retrieving data from the "bank1" database { try { MetaData1 ...

Angular2 - How to track or listen for (click) events on dynamically inserted HTML elements

I'm trying to inject a string with a dynamically retrieved (click) event into an Angular2 template. Since this string is fetched from the back-end after the DOM is loaded, Angular doesn't recognize the injected event. Here's an example of t ...

Guide to accessing a PHP web API (JSON) from an Android mobile application

Being new to Android, I have been tasked with creating a login function for a project using an existing webAPI that communicates in JSON format. However, I am unsure how to achieve this task as my attempts based on various examples have proven unsuccessful ...

Function in controller making an Ajax request

As a beginner in AngularJS, I am looking to implement a controller with a save function that makes an ajax call. This is how my current code looks: var app = angular.module("myApp1", []); app.controller("AddController", ['$scope', $http { ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...