0

I have the following function. The current output is name: "foo" surname: "bar"

How can I push my console log data to my payload

{
  name: "foo",
  surname: "bar
}

so the output becomes:

const ProcessHTML = (rawHtml, elements) => {
  const $ = cheerio.load(rawHtml);
  let payload = {}

  for (const data in elements) {
    let currentElement = $(elements[data]);
    let prettify = pretty(currentElement.html())
    console.log(`${data}: ${prettify}`)
  }
  return payload
};
JonJon
  • 169
  • 1
  • 1
  • 10
  • Sorry are you able to write an example. I read about it and still dont understand how to assign the key and value – JonJon Apr 20 '22 at 20:12
  • [Don't use `for…in` enumerations on array-like objects like `elements`!](https://stackoverflow.com/q/500504/1048572) – Bergi Apr 20 '22 at 20:14
  • Just do `payload[data] = prettify` instead of just logging it? – Bergi Apr 20 '22 at 20:15
  • @bergi thank you i was doing payload = { payload[data]: prettify } – JonJon Apr 20 '22 at 20:30
  • Yeah, that's not the correct syntax. You *could* do `payload = {...payload, [data]: prettify}`, but that would be weird. Just assign to the property. – Bergi Apr 20 '22 at 20:32

1 Answers1

-1

I can't understand if you are trying to output a single value in console or the full payload object, but I think is something like that:

const ProcessHTML = (rawHtml, elements) => {
  const $ = cheerio.load(rawHtml);
  let payload = {}

  elements.forEach( data => {    
    let prettify = pretty($(elements[data]).html());
    payload = Object.assing(payload, { data:prettify });
    console.log(`${data}: ${prettify}`)
  })

  return payload
};

If you need to output the entirely object, just change the console.log to console.log(payload)

GodFather
  • 3,031
  • 4
  • 25
  • 36