首页 > 解决方案 > 如何让我的代码排序数据从 Reddit 提取为 JSON 文本?

问题描述

[按属性值对对象数组进行排序]

我想比较赞成票的数量并进行排序,但是在理解如何从我的 api 中获取对象“ups”时遇到了问题。我创建了比较函数,我想调用它。我可能在错误的对象上调用它。

 function fetchData(url) {
    return fetch(url).then((resp) => resp.json());
}

function createTableRow(data) {
    const tableRow = document.createElement('tr');
    const {
        title,
        ups,
        downs,
        score,
        num_comments,
        created
    } = data;
    console.log(ups);
    tableRow.appendChild(createElement('td', title))
    tableRow.appendChild(createElement('td', ups))
    tableRow.appendChild(createElement('td', downs))
    tableRow.appendChild(createElement('td', score))
    tableRow.appendChild(createElement('td', num_comments))
    tableRow.appendChild(createElement('td', created))
    return tableRow;
}


function createElement(tag_name, text) {
    const el = document.createElement(tag_name);
    const content = document.createTextNode(text);
    el.appendChild(content);
    return el;
}

**function compare(a,b) {
    if(a.ups<b.ups) {
        return -1;
    }
    if(a.ups>b.ups){
        return 1;
    }
    return 0;
}** 


const butt = document.getElementById('button');

const swTable = document.getElementById('sw_table').getElementsByTagName('tbody')[0];


fetchData('https://www.reddit.com/r/funny.json')
.then(data => {
    data.data.children.forEach(result => {
    const table = createTableRow(result.data);
    swTable.appendChild(table);
   // butt.onclick(sortData(ups));
   **data.data.children.ups.sort(compare);**
});
});

错误:未捕获(承诺中)类型错误:无法读取未定义的属性“排序”

标签: javascriptarraysjsonapisorting

解决方案


这是您应该使用的:

fetchData('https://www.reddit.com/r/funny.json')
  .then(data => {
    const sortedResults = data.data.children.sort((a,b) => b.data.ups - a.data.ups)
    sortedResults.forEach(result => {
      const row = createTableRow(result.data);
      swTable.appendChild(row);
    })
  });
});
  • 您必须直接对结果进行排序
  • a.data.ups - b.data.ups如果 ups 多于则返回负数,如果aups 多于则返回b正数,如果bups数量a相同则返回 0

推荐阅读