[英]How to add items to a list and order by property in React or React Native
I am hoping to put my json data in a list and then add objects to the list and order everything by location我希望将我的 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"
}
]
What I have tried.我已经尝试过。 It works but wanted a better way to do it
它有效,但想要一个更好的方法来做到这一点
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]);
});
Basically we get a count of the blocks.基本上我们得到了块的计数。 Then we reorder the json by location.
然后我们按位置重新排序 json。 If there is a gap from 0-3 fill it in with placeholder data
如果从 0-3 有一个空白,用占位符数据填充它
Where you set the variable list const [list, setList] = useState([])
you are actually setting it to an empty array []
.在设置变量 list
const [list, setList] = useState([])
的地方,实际上是将其设置为空数组[]
。 But that's just a point about terminology.但这只是关于术语的一点。 You can sort the array using a sort function as follows.
您可以使用排序 function 对数组进行排序,如下所示。 But bear with me, I'm going to rename it array.
但请耐心等待,我将把它重命名为数组。
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.