Home > Enterprise >  how do i save the elements from forEach
how do i save the elements from forEach

Time:12-16

how do i save the element from for each. This code outputs the value to terminal how do I send it to res.send for postman.

            let cc = currencies.data.forEach(el => console.log(el.currency))
            let tz = timezones.default.forEach(el => console.log(el.label))
            res.status(200).send({
                status: true,
                status_code: 'SUCCESS',
                message: 'SUCCESS',
                currency: cc,
                timezones: tz,
            });

need to save el.currency and el.label

CodePudding user response:

You can use Array.prototype.map().

  1. Map the elements:
            let cc = currencies.data.map(el => cel.currency)
            let tz = timezones.default.map(el => el.label)
  1. Send them:
            res.status(200).send({
                status: true,
                status_code: 'SUCCESS',
                message: 'SUCCESS',
                currency: cc,
                timezones: tz,
            });

CodePudding user response:

@Mordor1110's answer is better — forEach doesn't return so you'd need an extra step like shown here. map does this by default so it's the right tool here. In JS sometimes you're iterating over collections that don't implement map (e.g. NodeList, which you get when you querySelectorAll something). In that case you have to resort to the "old" way (map is a more recent, ES6 addition to the language).


You could create an empty array before your first line and push to that in your loop

let cc = [];
let tz = [];
currencies.data.forEach(el => cc.push(el.currency))
timezones.default.forEach(el => tz.push(el.label))
res.status(200).send({
  status: true,
  status_code: 'SUCCESS',
  message: 'SUCCESS',
  currency: cc,
  timezones: tz,
});

console.log(cc, tz);
  • Related