I have an array of objects that can contain children of the same object type, like this:
var exampleArray = [
{
alias: 'alias1',
children: [
{
alias: 'child1'
},
{
alias: 'child2',
children: [
{
alias: 'child4'
},
{
alias: 'child5'
}
]
},
{
alias: 'child3'
}
]
},
{
alias: 'alias2'
},
{
alias: 'alias3',
children: [
{
alias: 'child6'
},
{
alias: 'child7'
}
]
}
];
The base object has other properties but they are not important to the question(s) at hand. For now, lets just assume the objects can be:
{
alias: 'string',
children: []
}
The children are optional.
I am looking for the best methods / fastest methods for managing some things with an object like this. I have created some recursive methods to do some of the things I want, but I want to know if there are better ways to go about doing the following tasks:
- hasAlias(arr, alias) - I need to determine if the entire object contains any object with the give alias.
Currently, I do this recursively but given that this array can grow finitely, the recursive method is eventually going to hit stack limits.
getParent(arr, alias) - I need to be able to obtain the parent that contains an element with the given alias. Given that alias' are unique to the entire array, there will never be two of the same alias. Again I do this recursively right now but I want to find better methods of doing this.
deleteObject(arr, alias) - I am unsure how to accomplish this one currently. I need to be able to pass an array and an alias and have that object (and all its children) removed from the given array. I started a recursive method of doing this but stopped and decided to post here instead.
I am using Node.js and have lodash available for faster methods of doing things. I'm still fairly new to JavaScript so I am unsure if there are better ways to go about doing things with larger scale arrays like this.
hasAliascould be done with something likeJSON.stringify(arr).indexOf('alias')if the wordaliasdoesn't appear anywhere else etc.