向Angular的JSON响应中添加新的对象属性

问题描述 投票:1回答:3

我正在尝试向JSON响应中添加新的对象属性。

我的示例JSON响应

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

获得响应后,需要向同一JSON响应添加新的对象属性(显示)

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

这是我的示例代码

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

但是控制台不断抛出以下错误:

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)
javascript angular typescript angular2-services
3个回答
2
投票

您的错误在这里

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

应该是

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

:)

https://jsfiddle.net/rt6LjvLa/


0
投票

这应该遍历对象数组:

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

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

}

小提琴:https://jsfiddle.net/echonax/dm1d0vyw/


0
投票

可能性1:

=循环中从<=中移除for,否则它将为未定义的对象再运行一次。

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

上面的解决方案不起作用,然后在下面的情况2中尝试]]

我怀疑res['products']返回了json array

运行下面的代码行,并将结果附加在这里:

console.log(res['products'])
for(var i = 0; i <= res['products'].length; i++){
    console.log(res['products'][i]);
    res['products'][i].show=false;
}
© www.soinside.com 2019 - 2024. All rights reserved.