1

I'm trying to add 100 items in an array, where each item contains a number (0-99) and a boolean, by achieving the result below using spread operator and the keys() method.

for(var i = 0; i < 100; i++){
    room.push({roomId: i, isAvailable: true});
}

Is it possible to add a boolean along with each item that was generated with keys()?

var room = [...Array(100).keys()] // to [{ roomId: 0, isAvailable: true }, ...]
Raithar
  • 13
  • 4
  • 1
    not without an additional map. .keys returns an iterator and ... spreads it. you'll have to add another step to map it to an object. `Array.from( Array(100), ( _, i ) => ({ roomId: i, isAvailable: true}) )` for example. – rlemon Jul 29 '19 at 16:57
  • [How to create an array containing 1…N](https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n) – Andreas Jul 29 '19 at 17:01

2 Answers2

1

You could use .fill() paired with .map() to get your expected result.

let rooms = Array(100)
    .fill()
    .map((_,roomId) => ({roomId, isAvailable: true}));

console.log(rooms);

With lodash you can use the _.times util:

let rooms = _.times(100, roomId => ({roomId, isAvailable: true}));
console.log(rooms);
<script src="https://unpkg.com/lodash@4.17.15/lodash.min.js"></script>
Turtlefight
  • 9,420
  • 2
  • 23
  • 40
0

You could take Array.from and take the index as id.

var length = 100,
    isAvailable = true,
    result = Array.from(
        { length },
        (_, roomId) => ({ roomId, isAvailable })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392