简体   繁体   中英

How do I loop through and add key values to values

I want to be able to loop through this object and add "key" values to the values so it can be easily used for a project. I'm Webscraping from a Website to get the data I have been able to get the data but I need to format it, here is my code and I'm stuck on what the next step is.

I'm trying to get it to look like this

EXAMPLE

  • server: "USSouth2"

  • cost: 100

  • howmuch: 56

  • time: 28

Code

let options = {
    url: 'https://www.realmeye.com/items/misc/',
    headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
    }
}
var result = [];
request(options, function(err, resp, html) {
    if (!err) {

        const $ = cheerio.load(html);
        let servers = $('.cheapest-server').attr('data-alternatives');

        servers.forEach(function(nexus) {
            result.push({
                servername: nexus[0],
                cost: nexus[1],
                howmuch: nexus[2],
                time: nexus[3]
            })
        })
    }
})

JSON object (this can change depending on the Website data)

["USSouth2 Nexus",100,56,28],["EUSouth Nexus",100,62,25],["AsiaSouthEast Nexus",100,58,25],["EUNorth2 Nexus",100,64,24],["EUEast Nexus",100,55,24],["USWest2 Nexus",100,73,23],["USMidWest2 Nexus",100,53,21],["USEast2 Nexus",100,98,17],["EUWest Nexus",100,66,11],["EUSouthWest Nexus",100,86,10],["USNorthWest Nexus",100,87,9],["USSouthWest Nexus",100,67,9],["EUWest2 Nexus",100,89,8],["USWest Nexus",100,66,8],["USSouth Nexus",100,54,7],["USMidWest Nexus",100,90,6],["USSouth3 Nexus",100,82,6],["USEast Nexus",100,65,1]]

I'm getting this error TypeError: servers.forEach is not a function

I haev updated the code snippet. please check now.

 let servers = [["USSouth2 Nexus",100,56,28],["EUSouth Nexus",100,62,25],["AsiaSouthEast Nexus",100,58,25],["EUNorth2 Nexus",100,64,24],["EUEast Nexus",100,55,24],["USWest2 Nexus",100,73,23],["USMidWest2 Nexus",100,53,21],["USEast2 Nexus",100,98,17],["EUWest Nexus",100,66,11],["EUSouthWest Nexus",100,86,10],["USNorthWest Nexus",100,87,9],["USSouthWest Nexus",100,67,9],["EUWest2 Nexus",100,89,8],["USWest Nexus",100,66,8],["USSouth Nexus",100,54,7],["USMidWest Nexus",100,90,6],["USSouth3 Nexus",100,82,6],["USEast Nexus",100,65,1]]; var result = []; servers.forEach(function(nexus) { result.push({ servername: nexus[0], cost: nexus[1], howmuch: nexus[2], time: nexus[3] }); }); console.log(result);

我已经修复它我忘了解析 JSON 这里是通过创建一个新变量的答案

let jsonData = JSON.parse(servers);

Okay, so if you know for sure the four keys will not change, then do something like this.

Create an array with the four keys in order of appearance in a single JSON array value. Use the map method of the array to loop over the array and manipulate each value and the and the reduce method to turn an array into object.

Check out the example below to see what it does.

 // Your JSON. const json = [["USSouth2 Nexus",100,56,28], ["EUSouth Nexus",100,62,25]]; // The four keys of the object. In order of the JSON array. const keys = ['servername', 'cost', 'howmuch', 'time']; // Loop over servers and return an object reduces from an array. const servers = json.map(server => server.reduce((acc, cur, i) => { let key = keys[i]; acc[key]= cur; return acc; }, {})); console.log(servers);

First of all, you need to check is servers are prsent and it's in form of array anf if so, then loop through the servers and get your data

const servers = $('.cheapest-server').attr('data-alternatives');

if (servers && Array.isArray(servers) && servers.length) {
  const result = [];
  for (let i = 0; i < servers.lenght; i += 1) {
    const entity = servers[i];
    const objBuilder = {
      servername: entity[0] || null,
      cost: entity[1] || null,
      howmuch: entity[2] || null,
      time: entity[3] || null,
    };  
    result.push(objBuilder);
  }
} else {
  // Error handling or pass an empty array
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM