4

I have the following Json structure on my project:

"disputas": [
    {
      id: "",
      tipo_negociacao: "",
      historico:[{
         fl_usuario: "",
         created_at: "",
         updated_at: "",
         created_by: null,
         updated_by: null,
         texto: "",
      }]
    }
]

I want to add a new index of historico when I click on a button but don't know how to do it, I want it to look like this:

 "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: "",
          }

       ]
    }
]

So far, I've done something like this (function that the button calls):

     recusaProposta() {
        this.disputa.historico[this.i].texto = "something";   
        this.i++;
}

now, since i starts on 0 this works on the first time I click on the button, but if I click on it again I'll get this error:

Cannot set property 'texto' of undefined

Can someone help me? thanks

Renê Silva Lima
  • 2,535
  • 2
  • 13
  • 20

4 Answers4

1

You run into the error

Cannot set property 'texto' of undefined

when you try to access a property on a undefined or null object.

You will first have to create a empty object in its place, if not already existing. The way your code is, it is expecting the object to be present in the index you are trying to access.

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";
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
1

Just append an array:

this.disputa.historico.push({/* your object here*/});
ghostprgmr
  • 488
  • 2
  • 11
1

Just push a new item to the historico array:

this.disputa.historico.push({
fl_usuario: "",
             created_at: "",
             updated_at: "",
             created_by: null,
             updated_by: null,
             texto: ""
});
Daniel AG
  • 320
  • 1
  • 9
0

Try this

disputas.historico.push({/* obj*/});
goto
  • 7,908
  • 10
  • 48
  • 58
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/15777175) – Ricardo Alvaro Lohmann Apr 07 '17 at 19:11
  • @RicardoAlvaroLohmann Link? What link? – Pang Apr 08 '17 at 04:07