`Obtaining an array of selected values from a deeply nested JSON object`

Looking to extract specific key values from a nested JSON object based on the boolean value of another key. In this case, I need the "name" key values for items where the "checked" key is true, and return them in a result array.

Here is an example of the JSON structure:

 const treeMetaData = [
{
  name  :  'database',
  checked : true,
  schemas  : [
    {
      name  : "schema1",
      checked : true,
      tables : [
        {
          name  : "table1",
          checked : true,
          columns : [
            {
              name  : "column1",
              checked : false,
            }, 
            {
              name  : "column2",
              checked : true,
            }
          ]
        },
      ]
    },
    {
      name  : "schema2",
      checked : true,
      tables : [
        {
          name  : "table2",
          checked : true,
          columns : [
            {
              name  : "column4",
              checked : true,
            }, 
            {
              name  : "column5",
              checked : false,
            }
          ]
        },
      ]
    },

  ]
}]

The desired output based on the provided data:

 ["database", "schema1", "table1", "column2", "schema2", "table2", "column4"]

I am seeking an optimized approach as the treedata is quite large in size. Any help would be greatly appreciated.

Answer №1

If you want to utilize recursion to retrieve the property with an array value and determine where to delve further:

const getListOfNames = arr =>
    arr.filter(({checked}) => checked).map(obj => {
        let value = Object.values(obj).find(value => Array.isArray(value));
        return [obj.name].concat(value ? getListOfNames(value) : []);
    }).flat()

const metadataTree = [{name  :  'database',checked : true,schemas  : [{name  : "schema1",checked : true,tables : [{name  : "table1",checked : true,columns : [{name  : "column1",checked : false,},{name  : "column2",checked : true,}]},]},{name  : "schema2",checked : true,tables : [{name  : "table2",checked : true,columns : [{name  : "column4",checked : true,},{name  : "column5",checked : false,}]},]},]}];
let result = getListOfNames(metadataTree);
console.log(result);

Answer №2

It appears to be a straightforward task, have you attempted using loops?

var result = [];

treeMetaData.forEach(database => {
    if(!database.checked){ return; }
    result.push(database.name);
    database.schemas.forEach(schema => {
        if(!schema.checked){ return; }
        result.push(schema.name);
        schema.tables.forEach(table => {
            if(!table.checked){ return; }
            result.push(table.name);
            table.columns.forEach(column => {
                if(!column.checked){ return; };
                result.push(column.name);               
            });         
        });     
    });
});

//result now holds: ["database", "schema1", "table1", "column2", "schema2", "table2", "column4"]

Answer №3

Embracing the power of nesting

const nestedData = [
{
  name  :  'category',
  checked : true,
  subcategories  : [
    {
      name  : "subcategory1",
      checked : true,
      items : [
        {
          name  : "item1",
          checked : true,
          details : [
            {
              name  : "detail1",
              checked : false,
            }, 
            {
              name  : "detail2",
              checked : true,
            }
          ]
        },
      ]
    },
    {
      name  : "subcategory2",
      checked : true,
      items : [
        {
          name  : "item2",
          checked : true,
          details : [
            {
              name  : "detail4",
              checked : true,
            }, 
            {
              name  : "detail5",
              checked : false,
            }
          ]
        },
      ]
    },

  ]
}]

const finalResult = []

nestedData.forEach(item => {
  if(item['checked']){
    finalResult.push(item['name'])
    let subcategories = item['subcategories']
    subcategories.forEach(subcategory => {
       if(item['checked']){
        finalResult.push(subcategory['name'])
        let items = subcategory['items']
        items.forEach(item => {
          if(item['checked']){
            finalResult.push(item['name'])
            let details = item['details']
            details.forEach(detail => {
              if(detail['checked']){
                finalResult.push(detail['name'])
              }
            });
          
          }
        });
       }
    });
    
  }
});

console.log(finalResult)

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

Modify data in a table using Dialog Component in Angular Material

I need to implement a Material Dialog feature that allows users to update entries in a table by clicking on the "Change Status" button. Check out this functional snippet: https://stackblitz.com/edit/angular-alu8pa I have successfully retrieved data fr ...

I tried utilizing the wrapper feature, but unfortunately, the modal did

import React, { PropTypes } from 'react'; import Dialog from 'material-ui/Dialog'; export default class CustomModal extends React.Component { constructor(props){ super(props) } handlePrimaryButton = () => { this.prop ...

Unraveling Nested JSON with Redshift and PostgreSQL

Attempting to extract 'avg' from a JSON text through the use of JSON_EXTRACT_PATH_TEXT() function. Here is a snippet of the JSON: { "data":[ { "name":"ping", "idx":0, "cnt":27, "min":16, ...

The HTML status code is 200, even though the JQuery ajax request shows a status code of 0

My issue is not related to cross site request problem, which is a common suggestion in search results for similar questions. When attempting to make an ajax request using jquery functions .get and .load, I'm receiving xhr.status 0 and xhr.statusText ...

Node.js - Passport authentication consistently results in redirection to failure route

I am currently working on creating a login form using passportJs, but I keep encountering the issue of failureRedirect. Despite searching on stack overflow for a solution, I have not found the correct answer yet. Below is my code: Here is how I am crea ...

How can we customize HTML images without allowing third-party JavaScript to enlarge them?

I am using Blogger to host my website and I have a basic knowledge of HTML and CSS. I want to incorporate a collaborative add-your-link feature using SimplyLinked. However... They provided me with the following HTML: <script type="text/javascript" src ...

Having trouble displaying the collection data from firebase using React

I am having an issue retrieving a collection from firebase and then using a map function to loop through the documents and render some UI elements. The data is correctly logged in the console at line 20, however, the map function doesn't seem to be wo ...

Using localStorage in Next.js, Redux, and TypeScript may lead to errors as it is not defined

Currently, I am encountering an issue in my project where I am receiving a ReferenceError: localStorage is not defined. The technologies I am using for this project are Nextjs, Redux, and Typescript. https://i.stack.imgur.com/6l3vs.png I have declared ...

Sending information through a form via a POST request after clicking on a hyperlink

I am attempting to submit a form using POST by clicking on a link and passing some hidden values. This is the code I'm currently using: $( document ).ready(function() { $('a#campoA').click(function() { $.post('testForm2.php', { ...

ESLint: The "react" plugin encountered a conflict

In my development environment, I have a React application within a single npm component package. This React app acts as a demonstration site that consumes the component package in addition to Storybook. local-component-package ├── .storybook ├─ ...

Using an image as a button in Vue.js: A step-by-step guide

I'm currently working on creating a login button within a single-file-component using Vue.js in my Rails application with a Vue.js front-end. The purpose of this button is to redirect users to an external login page when clicked. I am wondering how I ...

The hyperlink element is failing to load in a particular frame

I've been attempting to load the URL of an anchor tag in a specific frame. I've tried various methods through online searches, but have not found a satisfactory solution. Can someone please assist me with how to load the href URL in a particular ...

Approval still pending, awaiting response

Encountering an issue with a POST request using React and Express, where the request gets stuck in the middleware. I am utilizing CRA for the front end and Express JS for the backend. Seeking advice on troubleshooting this problem. Backend server.js var ...

Exploring the wonders of Vue.js and Laravel's type casting techniques

I have implemented DB2-style IDs for my database records in my Laravel 5.7 application, like this example: 201402241121000000000000. When trying to use it in my Vue component, I used the following syntax: <mycomponent v-bind:listing-key="{{ $listing-&g ...

Using Vue.js: Is there a way to apply scoped CSS to dynamically generated HTML content?

Summary: I'm struggling to apply scoped CSS styling to dynamically generated HTML in my Vue component. The generated HTML lacks the necessary data attribute for scoping, making it difficult to style with scoped CSS rules. Details: In a function cal ...

Exploring the world of Android development with Json and Volley beyond

My code successfully inserts data into MySQL using the following snippet: insert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { StringRequest request = new StringRequest(Request.Metho ...

The value of the input field in jQuery is not defined

I am encountering an issue with an error: jQuery input val() is undefined. I have 3 inputs that are all referencing one item. When I add a new row, I can create a new item (3 rows). All of these rows need to be organized in an array to be sent to a PHP f ...

experiencing an excessive amount of re-renders after transferring data to a distinct component

At the moment, I have implemented this logic to display data based on the results of a graphql query, and it is working well: const contacts = () => { const { loading, error, data } = useUsersQuery({ variables: { where: { id: 1 }, ...

Utilizing ng-class for dynamic routing and controlling

I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json: { "pages" : [ { "name" : "home" ...

Group By feature in AngularJS

Hey there, I'm trying to display a table from the code provided below. The issue I'm facing is with grouping by name. Here's how I want the view to appear: Shareholder | Preferred Stock | Common Stock | Options | Percentage | |----------- ...