Javascript 在 React 中对对象数组进行排序并渲染它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43572436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort an array of objects in React and render them
提问by KimR
I have an array of objects containing some information. I am not able to render them in the order I want and I need some help with that. I render them like this:
我有一个包含一些信息的对象数组。我无法按照我想要的顺序渲染它们,我需要一些帮助。我这样渲染它们:
this.state.data.map(
(item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)
Is it possible to sort them ascending with item.timeMin that map()-function or do I have to sort them before i use map?
是否可以item.timeM在该map()函数中对它们进行升序排序,还是必须在使用 map 之前对它们进行排序?
回答by Mμ.
This might be what you're looking for:
这可能是您正在寻找的:
// ... rest of code
// copy your state.data to a new array and sort it by itemM in ascending order
// and then map
const myData = [].concat(this.state.data)
.sort((a, b) => a.itemM > b.itemM ? 1 : -1)
.map((item, i) =>
<div key={i}> {item.matchID} {item.timeM}{item.description}</div>
);
// render your data here...
The method sortwill mutate the original array. Hence I create a new array using the concatmethod. The sorting on the field itemMshould work on sortable entities like string and numbers.
该方法sort将改变原始数组。因此我使用该concat方法创建了一个新数组。字段itemM上的排序应该适用于可排序的实体,如字符串和数字。
回答by Shubham Khatri
You will need to sort your object before mapping over them. And it can be done easily with a sort()function with a custom comparator definition like
在映射对象之前,您需要对它们进行排序。并且可以sort()使用带有自定义比较器定义的函数轻松完成,例如
var obj = [...this.state.data];
obj.sort((a,b) => a.timeM - b.timeM);
obj.map((item, i) => (<div key={i}> {item.matchID}
{item.timeM} {item.description}</div>))
回答by Vincenzo Centofanti
this.state.data.sort((a, b) => a.item.timeM > b.item.timeM).map(
(item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)
回答by Praveen prav
Chrome browser considers integer value as return type not boolean value so,
Chrome 浏览器将整数值视为返回类型而不是布尔值,因此,
this.state.data.sort((a, b) => a.item.timeM > b.item.timeM ? 1:-1).map(
(item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)
回答by Arun K
Try lodash sortBy
尝试 lodash sortBy
import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
console.log("application")
)
)
Read more : lodash.sortBy
阅读更多:lodash.sortBy

