Adding new data to JSON with Typescript and Angular

Asked

Viewed 209 times

0

I have a JSON that looks like this:

[
    {
        "texto": "Eae", 
        "contato": "Luis", 
        "data": "2018-09-25T21:08:00"
    },{
        "texto": "Salve povo", 
        "contato": "Rogerio", 
        "data": "2018-09-25T21:15:00"
    }
]

And an HTML component with a textarea where the user would enter the text and the missing data such as contact and date are dynamically caught.

How do I add a "message" to JSON to make it look something like this:

[
    {
        "texto": "Eae", 
        "contato": "Luis", 
        "data": "2018-09-25T21:08:00"
    },{
        "texto": "Salve povo", 
        "contato": "Rogerio", 
        "data": "2018-09-25T21:15:00"
    },{
        "texto": "De boas?", 
        "contato": "Victor", 
        "data": "2018-09-25T21:09:00"
    }
]

1 answer

0


You tried to use Array.push?

It would be something like:

meuArray.push({
    "texto": "De boas?", 
    "contato": "Victor", 
    "data": "2018-09-25T21:09:00"
});

or else

var objetoComAsInformacoesDesejadas = {
    "texto": "De boas?", 
    "contato": "Victor", 
    "data": "2018-09-25T21:09:00"
};
meuArray.push(objetoComAsInformacoesDesejadas);
  • I am trying to use an internal and private variable, like Httpclient this._http.get("../assets/db/mensagem.json"); ?

  • I don’t get it, buddy. Wasn’t the problem adding an item to the array? Your comment suggests that the problem may be another, unrelated to the question. If this is the case, I suggest asking a new question, clarifying the problem, with example of minimum code that reproduces it.

  • I need the dice typed (text) is played inside the JSON (the contact and date are taken dynamically by the application), for example I type "Hello" in the textarea and JSON should insert a new "message": {
 "texto": "Olá", 
 "contato": "Victor", 
 "data": "2018-09-27T14:10:00"
 }

  • If that’s it, the Array.push resolve. Just create an object with the desired elements and the text and push...

  • If you want to turn your object into text again, use the stringify

Browser other questions tagged

You are not signed in. Login or sign up in order to post.