Javascript 排序获取的数据

标签 javascript sorting

我正在制作这个菜单页面,使用 wordpress 作为后端。所以我获取了元素,将它们放入模板并将它们附加到父级,但现在我需要弄清楚如何按字母顺序对菜单项进行排序。我不知道是否应该在获取和追加之后编写新函数,或者将排序作为获取和追加数据的函数系列的一部分。

这是我用过的:

const template = document.querySelector("#menutemplate").content;
const newSection = document.createElement("section");
const parent = document.querySelector("main");

function getMenu() {
    fetch("MY LINK GOES HERE")
        .then(res => res.json())
        .then(showMenu)
}

function showMenu(menuItems) {
    //console.log(menuItems)
    menuItems.forEach(showItem)
}

function showItem(item) {
    //console.log(item)
    const clone = template.cloneNode(true);
    clone.querySelector(".product").textContent=item.title.rendered
    clone.querySelector(".price").textContent=item.acf.volunteer_price + " dkk";
    newSection.appendChild(clone);
    parent.appendChild(newSection);
}

getMenu();

最佳答案

你可以使用 Array.prototype.sort 吗?

function showMenu(menuItems) {
  menuItems
    .sort(a, b) => a.title.localeCompare(b.title))
    .forEach(showItem)
}

关于Javascript 排序获取的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53461641/

相关文章:

jsp内部html中的Javascript静态变量

javascript - 如何将按位运算应用于 JS 数字的实际 IEEE 754 表示?

scala - 使用 scala sortWith 函数对对象中的多个字段进行排序

javascript - Javascript 对象中的排序键

javascript - Jquery $.post() 变量作用域

javascript - 如何在 JavaScript 中为各种事件创建单个事件处理程序

Java 多维数组排序

c - 对结构数组进行排序

java - 二维数组排序

javascript - 如何将对象或变量值从html脚本标记传递到 Angular Controller