0

I have these lines of code to transform an array

const regex = new RegExp(req.params.keyword, 'i');
const fields = ['fname', 'lname'];
const arrayOfRegex = [];
// eslint-disable-next-line no-restricted-syntax
for (const f of fields) {
  arrayOfRegex.push({ f: regex });
}
console.log(arrayOfRegex);

My expected output is

[{ fname: /pyt/i }, { lname: /pyt/i }]

But I got this what went wrong?

[ { f: /pyt/i }, { f: /pyt/i } ]
Mohammed
  • 838
  • 6
  • 14
  • 1
    You need dynamic key, use square brackets `{ [f]: regex }` – Hassan Imam Feb 06 '22 at 08:35
  • There is nothing wrong with either `forEach` nor `for` (nor `for...of)`. The problem you describe is not at all related to any loop. In the future *be clear* what the problem is, do not attribute it to something unrelated. The point of asking a question is to provide something useful for other people to search for. Looking up problems with loops and finding information about building objects is not useful to them. – VLAZ Feb 06 '22 at 08:39

0 Answers0