[按属性值对对象数组进行排序]
我想比较点赞数和排序,但我无法理解如何从我的 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);**
});
});
错误: 未捕获( promise 中)类型错误:无法读取未定义的属性“排序”
最佳答案
这是您应该使用的内容:
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
如果a
的 ups 多于b
,则返回负数,a如果b
的 ups 数量多于a
,则为正数;如果它们的 ups 数量相同,则为 0
关于javascript - 如何让我的代码对从 Reddit 获取的 JSON 文本数据进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219914/