prosource

React에서 객체 배열 정렬 및 렌더링

probook 2023. 3. 29. 21:35
반응형

React에서 객체 배열 정렬 및 렌더링

정보가 포함된 객체 배열이 있습니다.원하는 순서대로 렌더링할 수 없기 때문에 도움이 필요합니다.다음과 같이 렌더링합니다.

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

오름차순 정렬이 가능합니까?item.timeM그런 점에서map()- 기능 또는 맵을 사용하기 전에 정렬해야 합니까?

이것은, 고객이 찾고 있는 것이기도 합니다.

// ... 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...

방법sort 는 원래의 어레이를 변환합니다.이 때문에, 새로운 어레이를 작성합니다.concat방법.필드에서의 정렬itemM문자열이나 숫자와 같은 정렬 가능한 엔티티에서 작동합니다.

개체를 매핑하기 전에 정렬해야 합니다.또한 이 작업은 쉽게 수행할 수 있습니다.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>))

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"
  }
]
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>
)

lodash 정렬 시도 기준

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

상세보기 : lodash.sortBy

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

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

정말 좋은 글을 찾았어요.반응: 객체 배열을 동적으로 정렬하는 방법

드롭 다운용이지만, 각색할 수 있습니다.중요한 것은 배열을 정렬하는 방법입니다.왜냐하면 포스트에서 설명한 것처럼 리액션은 요소가 같기 때문에 리스트 변경을 인식하지 않기 때문입니다.

const [currentList, setCurrentList] = useState(new Array());

const sorted = [...dataList].sort((a, b) => b["lotNumber"] - a["lotNumber"]).reverse();

setCurrentList(sorted);

문자열에는 local Compare를 사용합니다.많은 알파벳에서는 string.localeCompare 메서드를 사용하여 ö와 같은 문자를 적절히 정렬하는 것이 좋습니다.

예를 들어 독일어로 여러 국가를 정렬합니다.

let countries = ['Österreich', 'Andorra', 'Vietnam']
alert( countries.sort( (a, b) => a > b ? 1 : -1) )

이 경우 정렬된 배열의 결과는 다음입니다.안도라, 베트남 외스터라이치(잘못)

alert( countries.sort( (a, b) => a.localeCompare(b) ) )

한편, 다음과 같습니다.안도라, 외스터라이치, 베트남 (적절한)

이 접근방식은 나에게 효과가 있었다.

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

감사해요.

언급URL : https://stackoverflow.com/questions/43572436/sort-an-array-of-objects-in-react-and-render-them

반응형