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

0

4 Answers 4

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: ""
});
Sign up to request clarification or add additional context in comments.

Comments

1

Just append an array:

this.disputa.historico.push({/* your object here*/});

Comments

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";

2 Comments

Thanks for the answer, there are more simple solutions as I discovered now on the other answers, but this one makes sense and has a very nice explanation. Thank you
@RenêSilvaLima You are welcome :)
0

Try this

disputas.historico.push({/* obj*/});

2 Comments

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
@RicardoAlvaroLohmann Link? What link?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.