Ensure that there are no empty values within a nested object

Here is a data array structure that I am working with:

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

This structure can extend to multiple levels. In my Vue template, I have implemented a recursive method called validateNodes. This method checks if any object at any level has an empty name field (i.e., name: ''). If an empty name is found, it returns false; otherwise, it returns 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);
 }

However, when I try to print the 'valid' value in the console, it shows as undefined. Can someone please help me fix this issue?

Thank you in advance.

Answer №1

You don't actually utilize the outcome of a nested array.

Instead, you can validate using Array#every and consider nested children.

function checkNodes(tree) {
    return tree.every(node =>
        node.name &&
        (!node.children.length || checkNodes(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(checkNodes([]));
console.log(checkNodes([{ id: 1, name: 'someName', children: [] }]));
console.log(checkNodes([{ id: 1, name: '', children: [] }]));
console.log(checkNodes(data));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm struggling with my project called "Number TSP" and I can't seem to figure out why it's not working properly

Upon reaching the end of my code, I am encountering an issue where instead of seeing the expected output of "Done!", it displays undefined. This is the code in question: const container = document.querySelector(".container") const table = document.querySe ...

Explanation of JavaScript code snippet

fnTest = /abc/.test(function () { abc; }) ? /\bchild\b/ : /.*/; I am struggling to comprehend the functionality of this particular javascript snippet. Would someone be able to elaborate on the logic behind this code fragment? ...

Cross-building targets for Node modules for deployment on npm platform

I'm working on an ES6 module that needs to be compatible with different environments. I'm not sure whether to use webpack or rollup for building, and how to target specific environments. Building for Different Environments ES6 environments like ...

Angular CSS: ng-style applied to only one side, the other remains unaffected

I am working on an Angular application that requires a split screen with two halves, each displaying the same array values. The width and height values are set using a service and accessed by a controller. The style is applied using ng-style in the DOM. Ho ...

Error: Module 'fs' does not export the function 'existsSync' as requested

When I simulate the behavior of the fs module jest.mock('fs', () => { return { default: { readFileSync: () => { return CONTENT_DATA; }, existsSync: () => {}, }, }; }); Then I attempt to dynamically ...

I am trying to include the Css Baseline from @mui/material in my project. However, even though it is present in my JSON file, I am encountering an error stating that '@mui/material' needs to be included in the project

Struggling to import Css Baseline from @mui/material, it's listed in my json but I keep getting an error saying '@mui/material' should be included in the project's dependencies. I've been stuck on this issue for a while now! { &q ...

The jQuery closest selector seems to be malfunctioning when trying to scroll and focus on a specific class

My HTML code snippet is as follows: <div class="main"> <div class="sub-1"> <select> <option>1</option> <option>2</option> </select> </div> <div class="sub-2"> ...

Adjust the pagination length within the jQuery DataTables plug-in

I am looking to customize the pagination length in DataTables plug-in for jQuery. Specifically, I want to calculate the number of pages on the server side and display the correct amount of buttons on the client side. Can anyone provide guidance on how to ...

Encountering a 500 error in production when making a call to the Next.js API

I have a dedicated API folder within my next.js application to handle server-side endpoints: import { NextApiRequest, NextApiResponse } from 'next' import Cors from 'cors' // Setting up the CORS middleware const cors = Cors({ method ...

Adding text with jQuery

Currently, I am utilizing the Jquery text editor plugin known as JqueryTE. While adding some functions to it, I have encountered a roadblock. Specifically, I am attempting to insert additional text into the source of the textarea but have been unsuccessfu ...

What is the best way to retrieve the source code generated by Ajax

I designed a PHP script that generates text dynamically and returns it with a unique div id. However, when I use Ajax to retrieve this text as responseText, I am unable to access the properties of the div using JavaScript because the new text is not added ...

Ways to display or conceal text using Vanilla JavaScript

I am struggling to toggle text visibility using Vanilla JS. Currently, I can only hide the text but cannot figure out how to show it again. <button id="button">my button</button> <div> <p id="text">Hello</p& ...

How can I reset the search input in v-autocomplete (multiple) after selecting a checkbox from the drop-down menu?

I am facing an issue with the v-autocomplete component from Vuetify. Currently, when I enter "Cali" in the search input and select "California" from the dropdown list, the "Cali" value remains in the search input field. I need the entered value to be clear ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

Pressing the Enter key will result in data fetched from JSON being logged multiple times

I am currently implementing a search feature on my React website. When a user enters a keyword in the search input, the keyword is matched in a JSON file. If a match is found, it logs "yes" to the console; otherwise, nothing is logged. Here is an example ...

What are some inquiries regarding using `Date.now()` to initiate `useState`?

Utilizing an API to fetch the most recent posts from Firestore has been a crucial aspect of my project. The structure of the API function is outlined below: function loadFeedPosts( createdAtMax, limit ) { return db .collection("posts") .orde ...

Clicking on the v-progress-linear component causes the value to update

Whenever I clicked on my <v-progress-linear>, it would change, and I was looking for a way to prevent that. <v-progress-linear v-model="progress" color="primary" height="20" > Solution: Instead of using ...

A guide on extracting information from a personal Flask JSON route endpoint with Axios

I am looking to store JSON data in a variable using Axios in Javascript. The JSON endpoint is generated by my own server's route http://123.4.5.6:7890/json. I have been successful with this function: async function getClasses() { const res = await ...

Choose elements from one array by evaluating a boolean condition on a separate array

Given the array below: array([ nan, nan, nan, 1., nan, nan, 0., nan, nan]) It is created using the following code: import numpy as np row = np.array([ np.nan, np.nan, np.nan, 1., np.nan, np.nan, 0., np.nan, np.nan]) The goal is to f ...

When troubleshooting AJAX in Chrome, only the library lines are displayed in the call stack

While using "XHR breakpoints" to identify which line is triggering an AJAX request, I noticed that the call stack only shows Angular.js library lines. This makes it difficult to pinpoint the exact line in my code that triggered the request. What steps shou ...