我正在尝试向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)
您的错误在这里
for(var i = 0; i <= res['products'].length; i++)
应该是
for(var i = 0; i <res['products'].length; i++)
:)
这应该遍历对象数组:
for(var key in res['products']){
res['products'][key].show=false;
}
可能性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;
}