簡體   English   中英

如何在 React 或 React Native 中將項目添加到列表並按屬性排序

[英]How to add items to a list and order by property in React or React Native

我希望將我的 json 數據放入列表中,然后將對象添加到列表中並按位置排序所有內容

const [list, setList] = useState([])

const blocks = 4

const placeholder = [{ action : null, location : null, title : null }]

const json = [
  {
    "action": "go back",
    "location": 0,
    "title": "first Demo"
  },
  {
    "action": "press go",
    "location": 2,
    "title": "Second"
  }
]

Output I am hoping for when I console.log(list)

[
  {
    "action": "go back",
    "location": 0,
    "title": "first Demo"
  },
  {
    "action": "none",
    "location": 1,
    "title": "first Demo"
  }, 
  {
    "action": "press go",
    "location": 2,
    "title": "Second"
  },
  {
    "action": "none",
    "location": 3,
    "title": "first Demo"
  }
]

我已經嘗試過。 它有效,但想要一個更好的方法來做到這一點

const jsonValue = await AsyncStorage.getItem('@custom_layout');
      if (jsonValue != null) {
        const createPallet = Array.from({length: blocks}, (v, i) => ({
          title: null,
          icon: null,
          UUID: i,
          location: i,
          Children: [],
          action: null,
        }));

        JSON.parse(jsonValue).map((item, i) => {
          //Find index of specific object using findIndex method.
          const objIndex = createPallet.findIndex(
            obj => obj.location === item.location,
          );

          //Update object's.
          createPallet[objIndex] = item;

          // This will update your state and re-render
          setItems([...createPallet]);
        });

基本上我們得到了塊的計數。 然后我們按位置重新排序 json。 如果從 0-3 有一個空白,用占位符數據填充它

在設置變量 list const [list, setList] = useState([])的地方,實際上是將其設置為空數組[] 但這只是關於術語的一點。 您可以使用排序 function 對數組進行排序,如下所示。 但請耐心等待,我將把它重命名為數組。

const [array, setArray] = useState([]);

//Now you can add missing blocks.
for(let i=0; i<blocks; i++){
   if(!json.find(element=>element.location==i)){
      const newplaceholder = placeholder[0];
      newplaceholder.location = i;
      json.push(newplaceholder)
   }
}


//This is your sort function
const sortArray = (a, b)=>{
   return a.location-b.location
}

//When you want to use it to sort the array
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
json.sort(sortArray)

//Once you've added the placeholders and sorted the array
setArray(json);


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM