I am attempting to develop two recursive functions to "iterate" over an array of objects as shown below. I believe the two functions are quite similar, but they serve different purposes.
Function 1 is designed to update the object - it can modify every field in the "found" object and then return the "new" array of objects. Therefore, the function needs to locate the appropriate object by its .id
Function 2 is meant to find the object based on its .id and delete that object from the array, before returning the updated array of objects.
I have experimented with various methods (below the array of objects) but unfortunately, I am unable to successfully return the new object.
It's worth noting that even if each object has different keys, there will always be an .id key.
[
{
"type":"section",
"name":"Section 1",
"hassection":[
{
"type":"section",
"id":1,
"name":"Section 1 child section 1",
"hasMenuItem":
[
{
"type":"item",
"id":2,
"name":"Item 1",
"prices":
{
"type":"price",
"price":"15.95"
},
"description":"Blah Blah..."
},{
"type":"item",
"id":3,"name":
"Item 2",
"prices":[
{
"type":"price",
"price":"24.95"
},{
"type":"price",
"price":"13.95"
}
],
"description":"Blah Blah..."
}
]
},{
"type":"section",
"id":4,
"name":"Section 1 child section 2",
"hasitem":[
{
"type":"item",
"name":"Item 3",
"prices":
{
"type":"price","price":"14.50"
},
"description":"Blah Blah..."
},{
"type":"item",
"id":5,
"name":"Item 4",
"prices":
{
"type":"price",
"price":"14.50"
},
"description":"Blah Blah..."
}
]
},
]},{
"type":"section",
"name":"Section 2",
"hassection":[
{
"type":"section",
"id":6,
"name":"Section 2 child section 1",
"hasitem":[
{
"type":"item",
"id":7,
"name":"Item 5",
"prices":
{
"type":"price",
"price":"15.95"
},
"description":"Blah Blah..."
},
{
"type":"item",
"id":8,
"name":"Item 6",
"prices":
{
"type":"price",
"price":"13.95"
},
"description":"Blah Blah..."
}
]
}
]}
]
My function for updating
function updateNestedObj(obj,updates) {
const updateToApply = updates.find(upd => upd.id === obj.id);
if (updateToApply) {
// UPDATE THE OBJECT
}
for(let k in obj) {
if (typeof(obj[k]) === 'object') {
// ITERATE THROUGH THE OBJECT
updateNestedObj(obj[k], updates);
}
}
return updateToApply
}
My function for deleting
function deleteNestedObj(obj, updates) {
const updateToApply = updates.find(upd => upd.id === obj.id);
if (updateToApply) {
delete upd;
}
for(let k in obj) {
if (typeof(obj[k]) === 'object') {
deleteNestedObj(obj[k], updates);
}
}
}
I am struggling to figure out how to properly implement these functions - any assistance would be greatly appreciated. Thank you in advance!