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
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. If there is a gap from 0-3 fill it in with placeholder data
from Recent Questions - Stack Overflow https://ift.tt/3FK47IM
https://ift.tt/eA8V8J
Comments
Post a Comment