# More elegant solution to create a array of fake data

I am creating fake data using faker.js. Out of simplicity I created a for-loop.

const faker = require("faker")
const dataLength = 10
const productArr = []

for (var index = 0; index < dataLength; index++) {
productArr.push({
name: faker.commerce.productName(),
category: faker.commerce.department(),
price: faker.commerce.price(),
description: faker.lorem.paragraph(),
})
}

console.log(productArr.length)
console.log(JSON.stringify(productArr))

Is there a more elegant solution to iterate through an array that has a fixed length?

• This looks quite elegant to me. However, you're not "iterating through an array", you are creating an array. – KIKO Software Jun 5 '19 at 19:09

Since you're iterating for the sole purpose of creating an array, map is somewhat appropriate here.

const productArr = [... Array(dataLength)] // Create a dummy array dataLength elements long
.map(_ => ({ // And map over it
name: faker.commerce.productName(),
category: faker.commerce.department(),
price: faker.commerce.price(),
description: faker.lorem.paragraph(),
}));


I'm mentioning it just in case you aren't aware of map, but it could be argued that this exact usage is an abuse of the function. Really, map is for transforming one list into another list of the same length. In this case though, we're completely ignoring the original contents of the array being iterated over (shown by the fact that the parameter is called _).

I can't say I necessarily recommend map in this case, but I thought I'd mention it.

If however you ever wanted to enumerate the data you're producing, it would be appropriate:

const productArr = [... Array(dataLength).keys()] // [0, 1, 2, 3, ...]
.map(i => ({
i: i, // And use the parameter this time
name: faker.commerce.productName(),
category: faker.commerce.department(),
price: faker.commerce.price(),
description: faker.lorem.paragraph(),
}));