Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
Looping over data to create an array of objects

I'm looping over rows inside a table that has two tds. I'm getting the correct data inside the array, but I want to put each loop inside an array of objects with key value pairs.

This is what I have so far:

            let test = await page.evaluate(() => {
            let dataStructure = []

            for (let i = 1; i < 13; i++) {
                let main = document.querySelector(".test > table > tbody > tr:nth-child(" + i + ")")
                let data = main.querySelectorAll("td + td")

                data.forEach((x) => {
                    dataStructure.push(
                        x.innerHTML
                    )
                })
            }
            return dataStructure
        })

The output looks like this:

 [
  '',
  '',
  '',
  'Chicago',
  'IL',
  '',
  'US',
  '(12.34567, -12.34567)',
]

But I'm trying to do something like this:

[
  {
  adresss: '',
  apt: '',
  message: '',
  city: 'Chicago',
  state: 'IL',
  zip: '',
  country: 'US',
  coordinates: '(12.34567, -12.34567)',
  }
]
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The simple way to do this (assuming the properties are always in the same order, etc.) would be to just assign the values to properties themselves so, for example...

// Let's say that 'data' is the array of values from the table.
// Adjust accordingly for the intended layout...
let dataObject = {
    address: data[0],
    apt: data[1],
    // Etc...
    coordinates: data[7]
}

There are various other ways this could be done (for example, you could iterate through an array of property names and use those as assignments)

// Again, assume 'data' is the input array...
// Define a list of property names...
let properties = ["address", "apt", "message", "city", "state", "zip", "country", "coordinates"];
// Create an empty object for storing the values...
let dataObject = {};
for(let v in data) {
    // Assign the value of the v'th data item to the v'th property name of the object
    dataObject[properties[v]] = data[v]
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Assuming that you have some attribute in your td element that can help provide the keys in the datastructure such as:

<td data-keyname="country">US</td>

 let test = await page.evaluate(() => {
    let dataStructure = []
    let obj = {}
    for (let i = 1; i < 13; i++) {
        let main = document.querySelector(".test > table > tbody > tr:nth-child(" + i + ")")
        let data = main.querySelectorAll("td + td")

        data.forEach((x) => {
            obj[x.getAttribute('data-keyname')] = x.innerHTML
        })
    }
    dataStructure.puch(obj)
    return dataStructure
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda