I have the necessity to modify a nested object-array structure which has always the same pattern knowing only the indexes to access that particular object I want to change.
Example JSON array:
[
{
"name":"bob",
"age":5,
"subRows":[
{
"name":"paul",
"age":10,
"subRows":[]
},
{
"name":"claire",
"age":20,
"subRows":[
{
"name":"carl",
"age":40,
"subRows":[]
}
]
}
}
]
I need to dynamically delete an object which can be different every time, let's say the one with name "carl", therefore to achieve this expected result:
[
{
"name":"bob",
"age":5,
"subRows":[
{
"name":"paul",
"age":10,
"subRows":[]
},
{
"name":"claire",
"age":20,
"subRows":[]
}
}
]
Knowing all indexes of the Json structure to access it:
let indexesArray = [0, 1, 0];
I've tried this:
const deleteObject = (jsonData, indexesArray) =>{
let pathToDelete = "jsonData[indexesArray[0]]";
for(let i=1; i<indexesArray.length(); i++){
pathToDelete += ".subRows["i"]";
]
pathToDelete = []; //empty the array removing "carl" object
return jsonData;
}
How can I make javascript process my variable pathTodelete created dynamically to delete a specific object? Are there better ways to do it (of course, my code doesn't work)?