I have a data array as given below
let data = [{ id: 1, name: '', children: [{ id: 11, name: '', children: [] }, { id: 12, name: '', children: [{ id: 121, name: '', children: [] }, { id: 122, name: '', children: [] }] },
{ id: 2, name: '', children: [{ id: 21, name: '', children: [] }, { id: 22, name: '', children: [{ id: 221, name: '', children: [] }, { id: 222, name: '', children: [] }] } ] } ];
So the above data can extend upto 'n-levels' so in my vue template I have defined a recursive method called validateNodes which is used to check if any of the object at any level has an empty name (ie) name: ''. If yes then it should return false else return true.
validateNodes(tree) {
if (tree.length) {
return tree.forEach((elem) => {
if (elem.name === "") return false;
return elem.children.length > 0
? this.validateNodes(elem.children)
: true;
});
} else {
return true;
}
},
validateWbs() {
let data = ....(value specified above);
const valid = this.validateNodes(data);
console.log(valid);
}
But I don't know due to some reason when I print the 'valid' in console its gives be undefined. Please help me fix this.
Thanks in advance
tree.foreach()will execute the code for each of the items intreeand will returnundefined. If you want to use the result of your loop you could usetree.map()(which returns the results of the iteration as array). Ortree.some(),tree.every(), depending on what you want...