Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
About javascript array

I want to get below result in the end.

[{x: '10', y: '5'}, {x: '8', y: '4'}]

I don't understand why the result get by the following code is

[{x: '8', y: '4'}, {x: '8', y: '4'}]

var test =[["10", "5"],["8","4"]];
var series = {};
var sample = [];
for (var i = 0 ; i < test.length ; i++){
  series.x = test[i][0];
  series.y = test[i][1];
  console.log(i);
  console.log(series);
  sample.push(series);
};
console.log(sample);

Can you give me some advice on what I lack?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

series is an object, what you have done in the loop basically change the value of members of series twice and push series into sample array twice. Since sample[0] and sample[1] point to the same object, they obviously have the same members, you can verify it with console.log(sample[0] === sample[1]).

about 4 years ago · Juan Pablo Isaza Relatório

0

Looks like you are pushing the references of the same object (i.e. series) into the array (i.e. sample) twice. That's why the two elements in the results list looks the same. You may want to make a little change (see below) to get what you want.

var test =[["10", "5"],["8","4"]];
var series; /* declare a new variable */
var sample = [];
for (var i = 0 ; i < test.length ; i++){
  series = {};  /* assign a new object */
  series.x = test[i][0];
  series.y = test[i][1];
  console.log(i);
  console.log(series);
  sample.push(series); /* push the reference of the new object for loop i */
};
console.log(sample);

about 4 years ago · Juan Pablo Isaza Relatório

0

Hello @shinobu you are doing a simple mistake you are not clearing the object inside object. I am adding a line to the code and it will solve it

var test =[["10", "5"],["8","4"]];
var series = {};
var sample = [];
for (var i = 0 ; i < test.length ; i++){
  series = {};
  series.x = test[i][0];
  series.y = test[i][1];
  sample.push(series);
};
console.log(sample);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda