如何遍历并将键值添加到值

时间:2019-08-16 18:19:55

标签: javascript node.js json cheerio

我希望能够遍历该对象并将“键”值添加到这些值,以便可以轻松地将其用于项目。我正在从网站上进行Web爬取以获取数据,但是我需要对其进行格式化,这是我的代码,因此我坚持下一步是什么。

我正试图让它看起来像这样

示例

  • 服务器:“ USSouth2”

  • 费用:100

  • 多少钱:56

  • 时间:28

代码

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对象(根据网站数据可能会改变)

["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]]

我收到此错误 TypeError: servers.forEach is not a function

4 个答案:

答案 0 :(得分:0)

我更新了代码段。请立即检查。

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

答案 1 :(得分:0)

我已修复它,我忘了解析JSON,这是通过创建新变量来解决的问题

let jsonData = JSON.parse(servers);

答案 2 :(得分:0)

好的,因此,如果您确定四个键不会改变,请执行以下操作。

使用四个键在一个JSON数组值中按出现顺序创建一个数组。使用数组的map方法在数组上循环并操纵每个值,然后使用reduce方法将数组变成对象。

查看下面的示例以查看其作用。

// 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);

答案 3 :(得分:0)

首先,您需要检查服务器是否存在,如果是,则采用数组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
}

相关问题