8

I am using the faker.js library to generate random data and I have a couple of factory functions that generate a series of user data:

const createUser = () => {
  return {
    name: faker.name.findName(),
    email: faker.internet.email(),
    address: faker.address.streetAddress(),
    bio: faker.lorem.sentence(),
    image: faker.image.avatar(),
  };
};

const createUsers = (numUsers = 5) => {
  return Array(numUsers).fill(createUser());
};

let fakeUsers = createUsers(5);
console.log(fakeUsers);

The problem with this Array.fill approach is that it returns the same data n number of times. I want 5 different users to be returned from my factory.

How do I do this?

Penny Liu
  • 7,720
  • 5
  • 40
  • 66
Amit Erandole
  • 10,436
  • 20
  • 60
  • 92

4 Answers4

8

Array.from allows you to create an array and initialize it with values returned from a callback function in one step:

const createUsers = (numUsers = 5) => {
    return Array.from({length: numUsers}, createUser);
}
le_m
  • 15,910
  • 7
  • 55
  • 65
6

Create an array with blanks, and then use .map() to create users:

const createUsers = (numUsers = 5) => {
    return Array(numUsers)
        .fill(null)
        .map(createUser);
}
Aron
  • 6,128
  • 4
  • 24
  • 46
3

Creating an array via the Array constructor will yield an non mappable (or iterable for that matter) array.

This happens because the constructor will give you an array with X uninitialized values, causing map to fail. Using fill to initialize the values, even if initialized to null or undefined, will work:

const createUser = () => {
  return {
    name: faker.name.findName(),
    email: faker.internet.email(),
    address: faker.address.streetAddress(),
    bio: faker.lorem.sentence(),
    image: faker.image.avatar()
  }
}

const createUsers = (numUsers = 5) => {
  return new Array(numUsers)
    .fill(undefined)
    .map(createUser);
}

let fakeUsers = createUsers(5)
console.log(fakeUsers)

https://jsbin.com/punesorico/edit?html,js,console

Gorka Hernandez
  • 3,412
  • 17
  • 27
1

Here is another way of doing this job by a TCO recursive function;

function getFakeObject(){
  return Array(5).fill()
                 .reduce(o => Object.assign(o,{[String.fromCharCode(...Array(5).fill().map(_ => ~~(Math.random()*26)+65))] : String.fromCharCode(...Array(5).fill().map(_ => ~~(Math.random()*26)+97))}),{});
}

function makeFakeObjectsArray(n, r = []){
 return n ? makeFakeObjectsArray(n-1,(r.push(getFakeObject()),r)) : r;
}

console.log(makeFakeObjectsArray(5));
Redu
  • 19,106
  • 4
  • 44
  • 59