【发布时间】:2022-01-03 22:52:42
【问题描述】:
我希望将我的 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 之间有间隙,则用占位符数据填充它
【问题讨论】:
-
您尝试过什么了吗?你有什么问题吗?
-
我尝试了循环和映射,但我是编码新手,而且非常混乱。它也不起作用我无法更新列表。 const myData = JSON.parse(jsonValue) let list for (let i = 0; i
标签: javascript reactjs react-native jsx