Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine forEach callback parameter with function parameter

I am trying to combine a forEach callback parameter (HTMLAnchorElement/HTMLTableCellElement objects) with a function parameter (string).

What I am doing is getting the href of an a tag in one function call, and then textContent of a td tag in another function call, using the same function.

Here is my code:

// example usage of function
await scraper.scraper(args, 'a[href]', 'href') // get href

await scraper.scraper(args, 'table tr td', 'textContent') // get textContent

// scraper function
const scraper = async (urls, regex, property) => {
  const promises = []
  const links = []

  urls.forEach(async url => {
    promises.push(fetchUrls(url))
  })

  const promise = await Promise.all(promises)
  promise.forEach(html => {
    const arr = Array.from(new JSDOM(html).window.document.querySelectorAll(regex))
    arr.forEach(tag => {
      links.push(tag.href) // how about textContent?
    })
  })

  return links
}

Is there a way of some how combining the callback parameter tag from the forEach with the function parameter property?

The code below works. But what if I want to do further function calls to other properties? I don't want to add an if statement every time I make another function call, that kind of defeats the purpose of my function to be reusable.
property === 'textContent' ? links.push(tag.textContent) : links.push(tag.href)

Any attempt in trying to combine the two seems to go wrong. Is it not possible?


1 Answers

Use the property value you pass in as computed key of your el object (tag in your code), in order to pass the property value for the element inside the forEach dynamically, depending on the property you passed in

arr.forEach(el => {
  links.push(el[property]);
})
like image 110
quirimmo Avatar answered Jul 16 '26 08:07

quirimmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!