foshesco
foshesco

Reputation: 23

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)',
  }
]

Upvotes: 0

Views: 69

Answers (2)

JaivBhup
JaivBhup

Reputation: 855

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
})

Upvotes: 0

Delta
Delta

Reputation: 521

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]
}

Upvotes: 1

Related Questions