Array of objects on a json - http put
本问题已经有最佳答案,请猛点这里访问。
我的项目中有以下JSON结构:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | "disputas": [ { id:"", tipo_negociacao:"", historico:[{ fl_usuario:"", created_at:"", updated_at:"", created_by: null, updated_by: null, texto:"", }] } ] | 
我想在单击某个按钮时添加一个新的EDOCX1[0]索引,但不知道如何添加,我希望它看起来像这样:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | "disputas": [ { id:"", tipo_negociacao:"", historico:[{ fl_usuario:"", created_at:"", updated_at:"", created_by: null, updated_by: null, texto:"", }, { fl_usuario:"", created_at:"", updated_at:"", created_by: null, updated_by: null, texto:"", } ] } ] | 
到目前为止,我已经做了类似的事情(按钮调用的函数):
| 1 2 3 4 |      recusaProposta() { this.disputa.historico[this.i].texto ="something"; this.i++; } | 
现在,由于
Cannot set property 'texto' of undefined
有人能帮我吗?谢谢
只需将新项目推送到Historica数组:
| 1 2 3 4 5 6 7 8 | this.disputa.historico.push({ fl_usuario:"", created_at:"", updated_at:"", created_by: null, updated_by: null, texto:"" }); | 
只需附加一个数组:
| 1 | this.disputa.historico.push({/* your object here*/}); | 
你遇到了错误
Cannot set property 'texto' of undefined
尝试访问未定义或空对象的属性时。
如果尚未存在,则必须首先在其位置创建一个空对象。您的代码是这样的,它期望对象出现在您试图访问的索引中。
| 1 2 3 4 5 6 7 8 9 | var existingObj = this.disputa.historico[this.i]; // if the value is falsy, then go ahead and create // an empty object at that index if(!existingObj) { this.disputa.historico[this.i] = {}; } existingObj.texto ="something"; | 
试试这个
| 1 | disputas.historico.push({/* obj*/}); |