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

427
Visualizações
how to form an array of arrays with data

I need to create an array of arrays like this:

var serviceCoors = [
    [50, 40],
    [50, 50],
    [50, 60],
];

from elements with datas:

<div data-latitude="10" data-longitude="20" class="service-points__map"></div>
<div data-latitude="20" data-longitude="10" class="service-points__map"></div>

I`m trying this:

var test = [];
$('.service-points__map').each(function () {
    var test2 = $(this).contents();
    var items = [];
    $.each(test2, function(i, val) {
        items.push(val.data);
    });
    test.push(items);
});

But it doesn't work. I have 2 arrays, but they are empty.

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

0

Oh, what you did is... var test2 = $(this).contents(); is not the right thing you need to use. You should be using .data() and destructure the object:

var test = [];
$('.service-points__map').each(function() {
  var { longitude, latitude } = $(this).data();
  test.push([longitude, latitude]);
});
console.log(test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-latitude="10" data-longitude="20" class="service-points__map"></div>
<div data-latitude="20" data-longitude="10" class="service-points__map"></div>

I got the output as:

[
  [ 20, 10 ],
  [ 10, 20 ]
]
about 4 years ago · Juan Pablo Isaza Relatório

0

Initially I was going to suggest jQuery's map method but - by design apparently - it automatically flattens the output which can only be solved by nesting your coordinates in another array. It also seems like it automatically coerces strings to numbers which is useful in your case but it seems to be making a lot of decisions that you might not want.

const out = $('div').map((i, el) => {
  const { latitude, longitude } = $(el).data();
  return [[ latitude, longitude ]];
}).toArray();

console.log(out);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-latitude="10" data-longitude="20" class="service-points__map"></div>
<div data-latitude="20" data-longitude="10" class="service-points__map"></div>

Native JS doesn't have this problem. Just pick up the elements, and iterate over them returning the new array of nested coordinates.

const divs = document.querySelectorAll('div');

const coords = Array.from(divs).map(div => {
  const { latitude, longitude } = div.dataset;
  return [ +latitude, +longitude ];
});

console.log(coords);
<div data-latitude="10" data-longitude="20" class="service-points__map"></div>
<div data-latitude="20" data-longitude="10" class="service-points__map"></div>

Additional documentation

  • Destructuring assignment
about 4 years ago · Juan Pablo Isaza Relatório

0

Alternatively, you can use plain JS instead of jQuery. All you need to do is to get elements, iterate over them, create an array of the attributes of each item, and push it into the test array.

const test = [];
const items = document.querySelectorAll('.service-points__map');
items.forEach(item => {
  test.push([
    parseInt(item.getAttribute('data-latitude')),
    parseInt(item.getAttribute('data-longitude')),
  ]);
});

console.log(test);
<div data-latitude="10" data-longitude="20" class="service-points__map"></div>
<div data-latitude="20" data-longitude="10" class="service-points__map"></div>

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