- Forums
- react
- V5 - React Usestate Update - Deep Level Nested Arrays
this post shows how to update the value of an array element in a deep array with objects [5322], Last Updated: Wed Aug 14, 2024
edw
Wed Aug 14, 2024
0 Comments
100 Visits
In this example, you can update on a deep level array alement:
For this example, we need to update element the second element in the Arr Array to 9: questions[currentQuestionIndex].solution.Arr[1] 0
Source: G:\xampp8\htdocs\laravel\StudentTodo\ionic-rowley\ionic-rowleyV2\src\components\advanced\Advanced.tsx
How To UPDATE:
function checkInput(e: any) {
console.log(`LINE 109 e=`, e.target.attributes['data-index'].value);
let loc = e.target.attributes['data-index'].value.split(',')
let i = loc[0]; // currentQuestionIndex
let i1 = loc[1]; // index
let i2 = loc[2]; // index3
let i3 = e.target.value;
setQuestions(
[
...questions, questions[i], questions[i].solution, ...questions[i].solution.Arr, ...questions[i].solution.Arr[i1], ...questions[i].solution.Arr[i1][i2] = i3
]
)
}
Usage (look at <input
{questions[currentQuestionIndex].solution.Arr.map(
(rowArr: any, index: number) => {
return (
<h1
key={`multiplicationParent${index}`}
style={{
clear: "both",
textAlign: "right",
float: "right",
margin: "10px",
}}
>
{rowArr.map((num: any, index3: number) => {
return (
<div
key={`multiplicationChild${index3}`}
style={{ float: "right" }}
>
<input
data-index={`${currentQuestionIndex},${index},${index3}`}
type="text"
className="inputAnswerRow"
maxLength={1}
value={num}
onChange={(e) => checkInput(e)}
/>
</div>
);
})}
{index ==
questions[currentQuestionIndex].solution.Arr.length - 1
? "+"
: ""}
</h1>
);
}
)}
/>
Declare Variable:
const [questions, setQuestions] = useState<any>([]);
Structure:
[
{
"topNumber": [
"2",
"8",
"8",
"8"
],
"solution": {
"Arr": [
[
9,
9,
9,
9
],
[
"0",
"6",
"7",
"7",
"5"
],
[
"0",
"0",
"0",
"0",
"0",
"0"
],
[
"0",
"0",
"0",
"6",
"7",
"7",
"5"
]
]
},