Incorporate a fresh attribute to the JSON data in an Angular API response

I'm currently working on updating my JSON response by adding a new object property.

Below is an example of my initial JSON response:

{
    "products": [{
        "id": 1,
        "name": "xyz"
    }]
}

My goal is to include a new object property called 'show' in the same JSON response:

{
    "products": [{
        "id": 1,
        "name": "xyz",
        "show": false
    }]
}

Here is a snippet of my code implementation:

import {Component,OnInit} from '@angular/core';
    import {Http, Response} from '@angular/http';
    import 'rxjs/Rx';
    @Component({
      templateUrl:'./electronics.html'
    })
    export class electronicsComponent{
      productListElectronics={};
        productListElectronicResponse: Object;
        error:Object;
        constructor(private http: Http) {
          this.productListElectronicResponse={};
            this.error={};
            http.get('../json/electronics/electronics.json').map((res: Response) => res.json()).subscribe(res =>
              {

                for(var i = 0; i <= res['products'].length; i++){
                    res['products'][i].show=false;
                  }
                  console.log(res);
           }, error => this.error = error );
      }
    }

However, I keep encountering the following error message in the console:

ERROR TypeError: Cannot set property 'show' of undefined
    at SafeSubscriber.http.get.map.subscribe._this.error [as _next] (products.component.ts:22)
    at SafeSubscriber.__tryOrUnsub (Subscriber.ts:238)
    at SafeSubscriber.next (Subscriber.ts:190)
    at Subscriber._next (Subscriber.ts:135)
    at Subscriber.next (Subscriber.ts:95)
    at MapSubscriber._next (map.ts:80)
    at MapSubscriber.Subscriber.next (Subscriber.ts:95)
    at XMLHttpRequest.onLoad (xhr_backend.ts:104)
    at ZoneDelegate.invokeTask (zone.js:398)
    at Object.onInvokeTask (ng_zone.ts:253)
    at ZoneDelegate.invokeTask (zone.js:397)
    at Zone.runTask (zone.js:165)
    at XMLHttpRequest.ZoneTask.invoke (zone.js:460)

Answer №1

Here is where you went wrong

 for(let i = 0; i < res['items'].length; i++)

The correct way is as follows

for(let i = 0; i < res['items'].length; i++)

:D

https://example.com/jsfiddle123

Answer №2

This code snippet demonstrates how to iterate through an array of objects and update a specific property:

for(var index in data['items']){

    data['items'][index].active=true;

}

Fiddle: https://jsfiddle.net/exampleuser/samplecode/

Answer №3

Possibility 1:

To prevent the for loop from running one extra time for an undefined object, remove the = in <=.

for(var i = 0; i < res['products'].length; i++){
    res['products'][i].show=false;
}

If the above solution does not work, try Possibility 2 below.

I have a suspicion that res['products'] is returning a json array.

Run the following code and share your results here:

console.log(res['products'])
for(var i = 0; i < res['products'].length; i++){
    console.log(res['products'][i]);
    res['products'][i].show=false;
}

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

Does this function only function on a singular div?

I need some help! I'm having trouble getting a function to trigger on the divs below the initial one. Any advice? ...

Tips for updating state and rendering in a function component in React Native:

I am attempting to update the state before rendering the component in a function component. While I have found suggestions to use the useEffect hook for this purpose, I am finding the information on the React official site somewhat perplexing. The docume ...

The mat-checkbox is failing to accurately reflect its checked state

This code snippet is from my .html file: <mat-checkbox [checked]="getState()" (change)="toggleState()">Example Checkbox</mat-checkbox> <br><br> <button mat-raised-button color="primary" (click)=" ...

"How to dynamically fill a text input field from a table using jQuery when a specific value is selected, potentially involving multiple rows (possibly

Scenario I created a form that allows users to place orders for articles. These articles are displayed in a table within another form, where each article is listed with its code, description, and price. The goal is for users to select an article from th ...

Defining a structure for an entity in which its attributes distinguish between different data types and an array combination

I strongly believe that the best way to showcase this concept is through a clear example: enum EventType { A, B, C }; type MyEvent = [EventType.A, number] | [EventType.B, string] | [EventType.C, number, string]; const eventsGrouped: Record<Event ...

Reading JSON documents in JavaScript through multiline strings

Having a JSON document with multiline string data is causing issues for me. I have attempted multiple options, but none of them have successfully solved the problem. For example: [ { "someString" : "A rather long string of English text, an error m ...

Is there a function return type that corresponds to the parameter types when the spread operator is used?

Is it possible to specify a return type for the Mixin() function below that would result in an intersection type based on the parameter types? function Mixin(...classRefs: any[]) { return merge(class {}, ...classRefs); } function merge(derived: any, ... ...

New behavior in Vue 3: defineEmits is causing issues with defineProps data

Currently, I am working with Vue 3 and TS 4.4. In one of my components, I am using defineProps to define prop types. However, when I try to add defineEmits, VS Code starts indicating that my props variable is not recognized in the component template. Below ...

Using the express.Router instance for handling errors can be a useful tool in your development

Based on the documentation, it states that any nodejs express middleware function has the capability of being swapped out by App or Router instances: Given that router and app adhere to the middleware interface, they can be used just like any other midd ...

Are JavaScript Object notation and proper JSON the same thing?

When I execute valid JSON in the Chrome console: {"aaa":"bbb"} I encounter this error: SyntaxError: Unexpected token : But if I try something like this instead: {aaa:"bbb"} No error is thrown. Additionally, when running the following code ...

Is there a way to convert a File into a byte array and then save it in a database using Angular and ASP.Net Core?

Hey everyone, I'm fairly new to working with Angular and I've hit a roadblock when trying to implement file-upload functionality in my Angular application. The technologies I am using include Angular, ASP.Net Core, and Sqlserver. I am tasked wi ...

JQuery If Statement always outputs a consistent number regardless of the input provided

I'm facing an issue with my HTML form and JQuery code that is supposed to calculate a figure. The problem I am encountering is that the if statement always returns the same number, regardless of the input: $(document).ready(function() { ...

Using v-for with nested objects

Have you been attempting to create a v-for loop on the child elements of the {song: "xxx"} object within the songs array? export const data = [ {id: "1", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : &apos ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

Transferring information from RSC to a nested child component using the Next.js application router

Currently, I am in the process of migrating a large Pages router next.js project to the App directory. However, I have encountered a common challenge for which I am struggling to find a suitable solution. Despite being accustomed to the convenience of Reac ...

Beware: Inaccessible code detected in Reactjs usage

Currently, I am working on a ReactJS project where I have integrated two components - PrescriptionIndex and PrescriptionNew. Let's start with the 'PrescriptionNew' component: import React, { Component } from 'react'; import Flo ...

Oops, it seems like the project is missing a `pages` directory. Please kindly create one in the project root. Thank you!

Initially, my project setup looked like this: public .next src pages components assets next.config.js It was functioning properly, but I made a structural change to the following: public src client next.config.js jsconfig.json pa ...

To pass an interface property as an argument to another functional component

How do I reference an interface property as a parameter value in another functional component? interface InterfaceProperties { interfaceProperty1Id: number, interfaceProperty1Name : string } const tabsInterfaces: Map<InterfaceDetailEnum, JSX.Elemen ...

Tips for efficiently playing a WAV file in JavaScript by building an AudioBuffer

I'm having trouble playing the WAV file located at this link. The file plays fine in VLC and the details show that it is a Mono IMA WAV APDCM Audio (ms) file sampled at 24000Hz with 16 bits per sample. However, when I try to play the file by embeddin ...

What is the best way to define a category in order to utilize a saved string as a variable for referencing it?

An object named CONFIG holds the following information: export const CONFIG = { buttonDestinations: { detailedStats: `detailedStats`, mealPlans: `mealPlans`, products: `products` }, buttonTexts: { detailedStats: ...