This is my object with multiple nested child objects. My requirement is to update all the path properties, of each and every object by prepending few more items onto the path array.
Example:
Original path array = "path": ["8.4139e5d6"]
What will be prepended = ["f.34284b8f"]
Updated prepended array = "path": ["f.34284b8f", "8.4139e5d6"]
Likewise, the path property of all objects should be updated.
How can I go through this complex object and update the path values?
{
"id": "2254285645109265838",
"created_at": "2022-07-08T06:43:10.198458Z",
"updated_at": "2022-07-08T06:43:10.198458Z",
"name": "richText",
"type": "",
"layout": [
{
"type": "richText",
"title": "richText",
"id": "8.4139e5d6",
"children": [
{
"id": "0.99fcfd44",
"title": "New",
"type": "text",
"props": {},
"children": [],
"expanded": false,
"path": [
"8.4139e5d6",
"0.99fcfd44"
]
}
],
"path": [
"8.4139e5d6"
],
"expanded": true
}
],
"inputs": [],
"outputs": [],
"settings": {},
"app": "2207269985154238407",
"library": "2226681003462624929"
},
I think I would write a function that can call its self to iterate over the entire object and children multiple times. You can also use Object.keys(obj) to access the keys of the object to check if the key is = "path".
Here is a quick function that does what I think you are looking for where data is your parent object and insert is the array to append into path.
const loopObject = (obj, insert) => {
if (typeof obj !== "object") return;
for (let key of Object.keys(obj)) {
if (key === "path") {
obj[key] = [...obj[key], ...insert];
} else if (typeof obj[key] === "object") {
loopObject(obj[key], insert);
} else if (typeof obj[key] === "array") {
obj[key].forEach((element) => {
loopObject(element, insert);
});
}
}
return obj;
};