Please help,
I want to make a method findChildByIdInData(data:any, childId:string)
where the data is any JSON main node that has children with Ids.
Simply, how to make a method that receives JsonNode and its child Id as parameters to find that object using angular.
In my case, I have a data as a node where I want to find its children’s objects (may be nested) by id.
Thanks for your time 🙂
Advertisement
Answer
Got the result by using the Recursively Traverse an Object method: this link helps me: https://cheatcode.co/tutorials/how-to-recursively-traverse-an-object-with-javascript.
the backendService:
// Verify the object isObject(value): any { return !!(value && typeof value === "object"); }; // Find object in node findNestedObject(object: {}, keyToMatch: String, valueToMatch: String): any { if (this.isObject(object)) { let entries = Object.entries(object); for (let i = 0; i < entries.length; i += 1) { const [objectKey, objectValue] = entries[i]; if (objectKey === keyToMatch && objectValue === valueToMatch) { return object; } if (this.isObject(objectValue)) { let child = this.findNestedObject(objectValue, keyToMatch, valueToMatch); if (child !== null) { return child; } } } } return null; };
and call that method in component as:
// Find the nested object by passing node, key, & value // the this.shop is your backend data or json let result = this.backendService.findNestedObject(this.data, "id", "dataId"); console.log("Result: ", result);