在React中对对象数组进行排序并渲染它们

时间:2017-04-23 14:33:31

标签: javascript reactjs

我有一个包含一些信息的对象数组。我无法按照我想要的顺序渲染它们,我需要一些帮助。我这样渲染它们:

this.state.data.map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

是否可以在item.timeM - 函数中使用map()对它们进行升序排序,还是在使用地图之前必须对它们进行排序?

8 个答案:

答案 0 :(得分:52)

这可能是您正在寻找的内容:

// ... 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)
    .map((item, i) => 
        <div key={i}> {item.matchID} {item.timeM}{item.description}</div>
    );

// render your data here...

方法sort will mutate the original array。因此,我使用concat方法创建了一个新数组。

答案 1 :(得分:6)

在映射对象之前,您需要对对象进行排序。使用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>))

答案 2 :(得分:3)

Chrome浏览器将整数值视为返回类型而非布尔值

extend-to-zoom

答案 3 :(得分:2)

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>
)

答案 4 :(得分:0)

尝试lodash sortBy

import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
    console.log("application")
    )
)

了解更多:lodash.sortBy

答案 5 :(得分:0)

const list = [
  { qty: 10, size: 'XXL' },
  { qty: 2, size: 'XL' },
  { qty: 8, size: 'M' }
]

list.sort((a, b) => (a.qty > b.qty) ? 1 : -1)

console.log(list)

输出:

[
  {
    "qty": 2,
    "size": "XL"
  },
  {
    "qty": 8,
    "size": "M"
  },
  {
    "qty": 10,
    "size": "XXL"
  }
]

答案 6 :(得分:0)

这种方法对我有用

const list = [
  { price: 10, plan: 'a' },
  { price: 2, plan: 'b' },
  { price: 8, plan: 'c' }
];
this.setState({ planList: list.sort((a,b)=> a.membership_plan_initial_price-b.membership_plan_initial_price)  });


render(){
   return(){
      <div>
          this.state.planList !== undefined && this.state.planList !== null && 
          this.state.planList !== '' && this.state.planList.map((ele, index) => {
              return (
                 <div key={index}> {ele.price}{ele.plan}</div>
              )
          })
      </div>
  }
}

谢谢

答案 7 :(得分:0)

this.state.data.sort((a, b) => a.objKey > b.objKey ? 1:-1).map((objKey, index)
相关问题