简体   繁体   English

我如何遍历并向值添加键值

[英]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"服务器:“USSouth2”

  • cost: 100费用:100

  • howmuch: 56多少:56

  • time: 28时间: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) JSON 对象(这可能会因网站数据而异)

["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我收到此错误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.创建一个具有四个键的数组,按出现在单个 JSON 数组值中的顺序。 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.使用数组的map方法遍历数组并操作每个值,使用 the 和reduce方法将数组转换为对象。

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首先,您需要检查服务器是否已发送,如果是,则为数组 anf 的形式,然后遍历服务器并获取您的数据

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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