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

183
Visualizações
initializing a javascript dictionary with empty arrays

I want to initialize a dictionary with k empty arrays (keys are integers from 0 to k-1), something similar to python comprehension list:

data = {k: [] for k in range(2)}

Is something possible in javascript? if not, what would be the best way to do it?

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

0

Yes, its possible to do that in just a single line in JS.

let data = {
  ...Array.from({ length: 2 }, () => [])
};

console.log(data);

You can also experiment it, here


Make a function of it.

It will be easier and reusable if you make a function of it. Here the example:

// traditional function
function generateData(howMany) {
  return {
    ...Array.from({ length: howMany }, () => [])
  };
}

// ES 6 function
const generateDataES6 = (howMany) => ({ ...Array.from({ length: howMany }, () => []) });

console.log("traditionnal:", generateData(4));
console.log("ES6:", generateDataES6(3));

Results:

enter image description here


References:

  1. Spread operator: MDN - Spread Syntax
  2. Array.from() : MDN - Array.from() and W3-School - JS Array.from()
about 4 years ago · Juan Pablo Isaza Relatório

0

In python

>>> {k: [] for k in range(2)}
{0: [], 1: []}

In javascript, you should do the following:

const data = {};
for (let k = 0; k < 2; ++k) data[k] = [];

console.log(data)

about 4 years ago · Juan Pablo Isaza Relatório

0

I believe your phyton statement will generate the output below

data = {k: [] for k in range(2)}

print(data)
// {0: [], 1: []}

In javascript, you can utilize .reduce() to achieve the same result.

data = [...Array(2).keys()].reduce((obj, d) => { obj[d] = []; return obj; }, {})

console.log(data)
// {0: [], 1: []}
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