Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

185
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda