【问题标题】:How to connect json file to nodejs for sorting如何将json文件连接到nodejs进行排序
【发布时间】:2021-06-23 02:56:16
【问题描述】:

我之前从未使用过带有 nodejs 和 ejs 的 json,所以请原谅我缺乏知识。我能够从 json 生成项目列表,但是当我按下下拉列表进行排序时,除了基于下面的 ejs 按 id 进行默认排序之外,它没有显示任何输出。我是不是连接错了json?

nodejs

router.get('/product', (req,res) =>{
    fs.readFile('items.json', function (error, data) {
            if (error) {
                res.status(500).end()
            } else {
                res.render('product.ejs', {
                    user: req.user,
                    stripePublicKey: stripePublicKey,
                    items: JSON.parse(data)
                })
            }
    })
})

ejs

<select id="sortMed" onChange="getSelectValue()">
                <option onClick="defaultSorting()">Default Sorting</option>
                <option onClick="sortingbyPrice()">Sorting by price</option>
                <option onClick="sortingbyAlphabet()">Sorting by alphabet</option>
            </select> 

   <div class="row">
            <div class="col-4">
                <div class="shop-items" id="output">
                    <% items.medicine.forEach(function(item){ %>
                        <div class="shop-item" data-item-id="<%= item.id %>">
                            <span class="shop-item-title"><%= item.name %></span>
                            <img class="shop-item-image" src="../assets/img/<%= item.imgName %>">
                            <div class="shop-item-details">
                                <span class="shop-item-price">$<%= item.price / 100 %></span>
                                <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                            </div>
                        </div>
                    <% }) %>
                </div>
            </div>
        </div>

javascript

function sortingbyPrice(){
        console.log("Sorting price")
        const itemsJson = JSON.parse(data)
        $.getJSON('items.json', function(data) {
            return sorted = items.medicine.sort((medA, medB) => medA.price - medB.price);
        });
    }   

items.json

{
    "medicine": [
      {
        "id": 1,
        "name": "Bioderma",
        "price": 5000,
        "imgName": "product_01.png"
      },
      {
        "id": 2,
        "name": "Chanca Piedra",
        "price": 2300,
        "imgName": "product_02.png"
      },
      {
        "id": 3,
        "name": "Umcka",
        "price": 4000,
        "imgName": "product_03.png"
      },
      {
        "id": 4,
        "name": "CetylPure",
        "price": 8700,
        "imgName": "product_04.png"
      },
      {
        "id": 5,
        "name": "CLACORE",
        "price": 5600,
        "imgName": "product_05.png"
      },
      {
        "id": 6,
        "name": "POO-POURRI",
        "price": 6800,
        "imgName": "product_06.png"
      },
      {
        "id": 7,
        "name": "Ibuprofen",
        "price": 6800,
        "imgName": "product_07.png"
      }
    ]
  }
  
  

【问题讨论】:

  • 你是如何在 sortbyPrice() 中读取 JSON 文件的?
  • 问题更像是我能够根据教程的学习在 ejs 中显示来自 json 的列表,但我不知道如何将 json 文件连接到 ejs 进行排序。我不认为是通过测试 console.log 阅读它
  • $.getJSON 中的返回没有任何好处。在那里你需要用新数据填充你的组件。

标签: javascript node.js json ejs


【解决方案1】:

你可以这样排序:

const mockJsonData = {
    "medicine": [
      {
        "id": 1,
        "name": "Bioderma",
        "price": 5000,
        "imgName": "product_01.png"
      },
      {
        "id": 2,
        "name": "Chanca Piedra",
        "price": 2300,
        "imgName": "product_02.png"
      },
      {
        "id": 3,
        "name": "Umcka",
        "price": 4000,
        "imgName": "product_03.png"
      },
      {
        "id": 4,
        "name": "CetylPure",
        "price": 8700,
        "imgName": "product_04.png"
      },
      {
        "id": 5,
        "name": "CLACORE",
        "price": 5600,
        "imgName": "product_05.png"
      },
      {
        "id": 6,
        "name": "POO-POURRI",
        "price": 6800,
        "imgName": "product_06.png"
      },
      {
        "id": 7,
        "name": "Ibuprofen",
        "price": 6800,
        "imgName": "product_07.png"
      }
    ]
  }
  
   const sortByPrice = () => {
      mockJsonData.medicine.sort((a, b) =>  a.price - b.price);
 }
sortByPrice();
console.log(mockJsonData.medicine);

  

现在,你已经得到了排序好的药物列表,用这个更新的值重新渲染 ejs 模板。

res.render('product.ejs', {
                    user: req.user,
                    stripePublicKey: stripePublicKey,
                    items: sortingbyPrice(data) // data from reading JSON file
                });

// you sorting function be like


function sortingbyPrice(data){
        return itemsJson.medicine.sort((a, b) =>  a.price - b.price);
}
 

另外,您可以查看here

【讨论】:

  • 如果我有不同类型的排序,我是否放置项目:JSON.parse(data)?
  • 没有必要,如果字符串化对象是有效的,JSON.parse 会将它们转换为 JSON。如果您按字母排序,则可以使用其他方法。如果这个答案对你有帮助,你可以投票。
  • 它在控制台日志中正确显示,但在我单击摊牌后并没有真正显示 ejs 的变化。但是谢谢你教我排序!
【解决方案2】:

我不太明白运行排序时 Json 的结构如何。
无论如何,我已经创建了这个小提琴,所以你可以检查一个 jsons 数组中的正确排序,类似于我期望你在节点后端得到的:

https://jsfiddle.net/9gpzwhs0/

console.log("Sorting price")
const itemsJson = [{
  medicine: {

    price: 2
  }
},
{
  medicine: {
    price: 1
  }
}
] 
console.log(itemsJson.sort((medA, medB) => medA.medicine.price 
- medB.medicine.price));

在排序中,我看到您正在执行 intems.medicine.sort,而您应该执行 items.sort 并在排序函数中返回 medA.medicine.price

【讨论】:

  • 如果我只是将json粘贴到ejs中并排序,或者在使用json进行排序时推荐哪种方法更好?
  • 这种排序方式还不错。这不会是一个巨大的开销,你可以依赖它。只需传递 json 并像普通数组一样对其进行排序。没关系
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多