0
\$\begingroup\$

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?

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

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

Resource for the "range" on the first line..

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.