Home > Software engineering >  initializing a javascript dictionary with empty arrays
initializing a javascript dictionary with empty arrays

Time:04-28

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?

CodePudding user response:

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)

CodePudding user response:

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: []}

CodePudding user response:

Yes. Its possible to do something similar to that in JS.

You can use .keys() method from an Array Object, then use the spread operator to the results. Then use .map() method so each of the element contain an empty array.

let data = {
  k: [...Array(2).keys()].map(() => []) // add map so it returns empty array
};

console.log(data.k);

You can try or experiment here: Codesandbox (already updated)


References:

  1. Spread operator: MDN - Spread Syntax
  2. Array .keys(): MDN - Array .keys() and W3Schools - JS Array keys()
  3. Array .map(): MDN - Array .map() and W3Schools - JS Array map()
  • Related