stackunderflow
stackunderflow

Reputation: 1714

Generate an array of UUID's in Javascript

Using a module such as uuid how could I generate the following structure.

[
    'd9baea4e-2436-4481-accb-7c2fe835039e',
    '60152666-8c2c-4d33-a5c8-da1dda106c5d', 
    'c4eaa558-83cc-4b94-9aff-1aefdc204794', 
    '273998e3-3138-41eb-b740-28ee53f7e344'
]

Would I be right in assuming this could be done with a Promise or at least could such an approach be given.

Upvotes: 0

Views: 4195

Answers (1)

Paul
Paul

Reputation: 36329

uuid is actually a synchronous function, per the docs. So a simple loop would do:

const uuidv4 = require('uuid/v4');
const ids = [];
for(let i=0;i<10;i++){
  ids.push(uuidv4());
}

Or you can also do a one-liner if you like:

const ids = Array(4).fill().map(() => uuid());

Upvotes: 7

Related Questions