Save an object inside an array without overwriting the old javascript

Asked

Viewed 369 times

1

I’m learning javascript and I’ve already broken my head a lot with this,I looked at several forums and questions here on the site but I couldn’t solve the problem.I want to take the value of two inputs and create an object with it and then save in an array,and then enter other values and do the same, only it is duplicating and not guarding each object. here and my html:

obj = {}
n1 = []

function pessoa() {
  obj.nome = document.getElementById('nome').value
  obj.idade = document.getElementById('idade').value

  n1.push(obj)
  console.log(n1)

  document.getElementById('res').innerHTML += `O nome digitado foi ${obj.nome} e a idade foi ${obj.idade}</br>`

  document.getElementById('nome').value = ""
  document.getElementById('idade').value = ""
}
<div class="container">
  <input type="text" id="nome">
  <input type="number" id="idade">
  <input type="button" value="enviar" onclick="pessoa()">
  <div id="res"></div>
</div>

html is storing, but when I look at the console this duplicated the object array

1 answer

0


This happens because you always work on the variable obj, with this, you always rewrite the values of the variable and add it again in the array, as all positions of the array point to the same variable, you end up having these same data.


A very simple way to correct this is to declare the variable obj within the function pessoa:

function pessoa() {
    let obj = {};

With this your final code will be more or less as follows:

let n1 = [];

function pessoa() {
    let obj = {};

    obj.nome = document.getElementById('nome').value;
    obj.idade = document.getElementById('idade').value;

    n1.push(obj);
    console.log(n1);

    document.getElementById('res').innerHTML += `O nome digitado foi ${obj.nome} e a idade foi ${obj.idade}</br>`;

    document.getElementById('nome').value = "";
    document.getElementById('idade').value = "";
}
<div class="container">
    <input type="text" id="nome">
    <input type="number"  id="idade">
    <input type="button" value="enviar" onclick="pessoa()">

    <div id="res"></div>
</div>

  • 1

    I don’t know how to thank you man, thank you very much, it was a whole afternoon reading a lot of stuff trying to avoid asking silly questions here.

Browser other questions tagged

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