繁体   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