我希望將我的 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 之間存在差距,則用占位符資料填充它
uj5u.com熱心網友回復:
設定變數串列的
const [list, setList] = useState([])地方實際上是將其設定為空陣列[]。但這只是關于術語的一點。您可以使用排序函式對陣列進行排序,如下所示。但是請耐心等待,我將重命名它為陣列。
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/367198.html
標籤:javascript 反应 反应原生 jsx
