1

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

1
  • tree.foreach() will execute the code for each of the items in tree and will return undefined. If you want to use the result of your loop you could use tree.map() (which returns the results of the iteration as array). Or tree.some(), tree.every(), depending on what you want... Commented Jan 11, 2021 at 13:45

1 Answer 1

2

You do not realy use the result of a nested array.

Instead you could check with Array#every and respect nested children.

function validateNodes(tree) {
    return tree.every(node =>
        node.name &&
        (!node.children.length || validateNodes(node.children))
    );
}

const 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: [] }] }] }] }];

console.log(validateNodes([]));
console.log(validateNodes([{ id: 1, name: 'someName', children: [] }]));
console.log(validateNodes([{ id: 1, name: '', children: [] }]));
console.log(validateNodes(data));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.