Inserting objects into an array through a loop

Asked

Viewed 131 times

1

I am with a problem that I am not able to solve at the moment. I am trying and I cannot reach a solution.

Basically I want to insert several objects into an array. What I’m doing is, I guess what I’m trying to do is wrong, what would be the right way to insert objects into the array? I think I’m also missing the push method:

const aniversario = []

  for (let i = 0; i <= 10; i++) {
      aniversario.push(i) = {
      nome: 'Thiago',
      idade: 20
      diaDoAniversario: '7/12/2020'
    }
    console.log('Aniversarios sendo inseridos', aniversario[i])
  }
  console.log('aniversario 8', aniversario[8])
  console.log('Total de itens', aniversario.length)

2 answers

2

The correct way using the method push is to pass the new object created integrally, example:

const aniversarios = []
aniversarios.push({ ... objeto criado});

Final example:

const aniversarios = []

for (let i = 0; i <= 10; i++) {
  const aniversario = {
    nome: 'Thiago',
    idade: 20,
    diaDoAniversario: '7/12/2020'
  };
  aniversarios.push(aniversario);
}
console.log(aniversarios); 
console.log('aniversario 8', aniversarios[8])
console.log('Total de itens', aniversarios.length)

2


I think you need to understand better what a function javascript.

Let’s check this part of the code:

aniversario.push(i) = {
  nome: 'Thiago',
  idade: 20
  diaDoAniversario: '7/12/2020'
}

Note that you are calling the method Array.prototype.push (push), passing the variable value i. This will insert (at the end of the array) the value of i every iteration, until the loop ends.

But note that at the return of the method push (which in this case is the new array length) you are trying to assign the literal object (note the assignment operator = which, in that case, is not doing anything useful). It is the same thing as trying to assign an object to a number, thus:

// Este código não faz sentido e lançará um erro de sintaxe.
1 = { name: 'Foo' };

This makes no sense since you want to insert the object into the array. Therefore, you should call the push passing, as argument, the very value you want to insert. In this case, it is the literal object itself.

You will then have something like this:

const aniversario = [];

for (let i = 0; i <= 10; i++) {
  aniversario.push({
      nome: 'Thiago',
      idade: 20,
      diaDoAniversario: '7/12/2020'
  });
}
console.log('aniversario 8', aniversario[8])
console.log('Total de itens', aniversario.length)

You can even use the assignment to insert some value in a array, but it is not very necessary, since the push does this for free. Anyway, to assign, you will need to use bracket notation:

let arr = [];
arr[0] = 'A';
arr[1] = 'B';
arr[2] = 'C';

console.log(arr); //=> ['A', 'B', 'C']
console.log(arr.length); //=> 3

Browser other questions tagged

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