I want to set a boolean value in a nested object structure, based on a list of indexes
The data I want to update looks like this:
let categories = [{
"name": "Cat 1",
"subs": [{
"name": "Sub Cat 1.1",
"subs": [],
"checked": false
},
{
"name": "Sub Cat 1.2",
"subs": [],
"checked": false
}
],
"checked": false
},
{
"name": "Cat 2",
"subs": [],
"checked": false
}
];
The indexes are stored in an array:
let categoryIndexs = [0,1]
So based on categoryIndexs I want to change the checked property of the object with name "Sub Cat 1.2" to true.
It is like transforming the array [0,1] to find categories[0].subs[1] and update its checked property.
So far I managed to get the value and edit it separately, but how to change the categories variable directly?
let categoryIndexs = [0,1]
let tmp_array = categories;
for(var i = 0; i < categoryIndexs.length;i++){
if(i == 0){
tmp_array = tmp_array[categoryIndexs[i]]
} else {
tmp_array = tmp_array.subs[categoryIndexs[i]]
}
}
tmp_array.checked = true
console.log(tmp_array)
The solution needs to be dynamic, so that if "Sub Cat 1.2" would have a nested entry in its own subs array, I can access it using categoryIndexs like [0,1,0]