简体   繁体   English

根据字符串参数对对象数组进行排序

[英]Sort array of objects based on string parameter

I have the following array of objects:我有以下对象数组:

   [
     {
       "id" : 1,
       "pricePerDay" : 50,
     }, 
     {
       "id" : 2,
       "pricePerDay" : 70   
     }
   ]

Based on the user input from ai want to filter either ASC or DESC on the pricePerday .基于 ai 的用户输入,希望在pricePerday上过滤 ASC 或 DESC。 Obviously this would work with:显然这适用于:

 this.products.sort((a, b) => parseFloat(b.pricePerDay) - parseFloat(a.pricePerDay));

BUT i have the variable filterType which now contains the string 'pricePerDay' .但是我有变量filterType现在包含字符串'pricePerDay' How can I use this variable to search the array of objects to properties that have the same key and sort this array based on that key?我如何使用此变量在对象数组中搜索具有相同键的属性并根据该键对该数组进行排序?

this.products.sort((a, b) => parseFloat(b[filterType]) - parseFloat(a[filterType]));

Does this answer your question?这回答了你的问题了吗?

You can change filterType to field that you want and acs to false if you want desc order您可以将 filterType 更改为您想要的字段,如果您想要 desc 顺序,则可以将 acs 更改为 false

 const arr = [ { "id": 1, "pricePerDay": 50, }, { "id": 2, "pricePerDay": 70 } ] let filterType = 'pricePerDay' let asc = false const res = arr.sort((a, b) => { if (asc) { return parseFloat(a[filterType]) - parseFloat(b[filterType]) } else { return parseFloat(b[filterType]) - parseFloat(a[filterType]) } }); console.log(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM