3

I'm trying to add a new object property to my JSON response.

My sample JSON response

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

After getting the response need to add new object property(show) to the same JSON response

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

This is my sample code

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 );
      }
    }

But console keeps on throwing the following error:

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)
1
  • 1
    Put a breakpoint on the line in question, wait for it to get there, then example values such as i or res['products'][i]. Commented May 8, 2017 at 8:09

3 Answers 3

2

Your mistake is here

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

It should be

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

:)

https://jsfiddle.net/rt6LjvLa/

Sign up to request clarification or add additional context in comments.

1 Comment

It would be so nice if there was a close reason for typos. Oh, wait a minute, there is.
0

This should work for traversing your array of objects:

for(var key in res['products']){

    res['products'][key].show=false;

}

Fiddle: https://jsfiddle.net/echonax/dm1d0vyw/

4 Comments

Using for...in for iterating over an array is generally frowned on.
@torazaburo if the keys are not indexes, how else are you going to traverse the object?
With an array, the keys are (almost always) indexes.
@torazaburo ah now I see that in will also traverse the prototype keys. Thanks for the reminder.
0

Possibility 1:

Remove = from <= from for loop else it would run one more time for undefined object.

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

It above solution does not work then try below Possibility 2

I suspect res['products'] returns an json array.

Run below lines of code and attach your result here:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.