简体   繁体   English

ReactJS:如何根据props的值对对象数组进行排序?

[英]ReactJS: How do I sort an array of objects based on value of props?

I have an array of React objects and I want to sort them based on value of one of their props. 我有一个React对象数组,我想根据其中一个道具的值对它们进行排序。

var arr=[];
arr[0] = <Fruit name="orange" count={10}/>
arr[1] = <Fruit name"apple" count={5}/>

Is there built in React function that I can use to sort this array in ascending order of fruit count ? 是否内置了React函数,我可以使用它来按照水果count升序对此数组进行排序?

React does not have a built in function to handle this (that I know of), but you could use something like lodash to achieve what you want. React没有内置函数来处理这个(我知道),但你可以使用像lodash这样的东西来实现你想要的。 I would also suggest that you change the structure of your data slightly. 我还建议您稍微更改数据结构。 Have a look at the example below. 看看下面的例子。

// your data comes in like this  
var arr = [
    {name: "orange", count: 10}, 
    {name: "apple", count: 5},
    {name: "lemon", count: 11},
    {name: "grape", count: 2}
];

// order by ascending
var newArr = _.sortBy(arr, 'count', function(n) {
  return Math.sin(n);
});

// create your components
var fruits = newArr.map(function(fruit) {
   return(
      <Fruit name={fruit.name} count={fruit.count} />
   );
});

Here is a fiddle to illustrate the sorting function input and output 是一个小提琴,用于说明排序功能的输入和输出

If you want to sort depending on multiple fields:- //using lodash 如果要根据多个字段进行排序: - //使用lodash

sortingFunction(arrayTobeSorted) {
let sortedResults = sortBy(arrayTobeSorted, function(e) {
return [e.field1.trim().toUpperCase(), e.field2.trim().toUpperCase()];
});

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

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