Generate an array with random data without using a for loop

拟墨画扇 提交于 2020-08-04 05:45:07

问题


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?


回答1:


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);
}



回答2:


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

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



回答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




回答4:


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));


来源:https://stackoverflow.com/questions/42861732/generate-an-array-with-random-data-without-using-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!