Parse and filter a nested array using JavaScript

Looking to extract using JavaScript: {"subNav0", "subNav1", "subNav2", "subNav3", "subNav4", "subNav5"}.

This is my JSON data:

 const jsonData = {
   "menus":{
      "GrandparentNav0":{
         "name":"TopNav",
         "items":[
            {
               "name":"ParentNav0",
               "iconClass":"",
               "items":[
                  {
                     "name":"ParentNav1",
                     "iconClass":"",
                     "items":[
                        {
                           "name":"subNav0",
                           "iconClass":""
                        },
                        {
                           "name":"subNav1",
                           "iconClass":""
                        },
                        {
                           "name":"subNav2",
                           "iconClass":""
                        },
                        {
                           "name":"subNav3",
                           "iconClass":""
                        },
                        {
                           "name":"subNav4",
                           "iconClass":""
                        },
                        {
                           "name":"subNav5",
                           "iconClass":""
                        }
                     ]
                  },
                  
               ]
            }
         ]
      }
   },
  
   
};

I have knowledge of basic array filtering:

jsonData.forEach(function(o) {
 o.variable = o.variable.filter(s => s.value == value);
 });

Unsure how to access menus from GrandparentNav0 in order to extract the subNav(s)

Answer №1

When you mention "pull the subNav(s)," are you referring to accessing it using bracket notation?


let subNavs = data['menus']['GrandparentNav0']['items'][0]['items']

console.log(subNavs)

/* The output would be:
[
  {
    "name": "subNav0",
    "iconClass": ""
  },
  {
    "name": "subNav1",
    "iconClass": ""
  },
  {
    "name": "subNav2",
    "iconClass": ""
  },
  {
    "name": "subNav3",
    "iconClass": ""
  },
  {
    "name": "subNav4",
    "iconClass": ""
  },
  {
    "name": "subNav5",
    "iconClass": ""
  }
]
*/

Answer №2

If you're looking for a solution that offers versatility, consider using object-scan. While it may seem like overkill for your current needs, it serves as a Swiss army knife for various data interactions, keeping the process neat and efficient.

// const objectScan = require('object-scan');

const data = { menus: { GrandparentNav0: { name: 'TopNav', items: [ { name: 'ParentNav0', iconClass: '', items: [ { name: 'ParentNav1', iconClass: '', items: [ { name: 'subNav0', iconClass: '' }, { name: 'subNav1', iconClass: '' }, { name: 'subNav2', iconClass: '' }, { name: 'subNav3', iconClass: '' }, { name: 'subNav4', iconClass: '' }, { name: 'subNav5', iconClass: '' } ] } ] } ] } } };

const result = objectScan(['menus.GrandparentNav0.items[0].items[0].items[*].name'], { reverse: false, rtn: 'value' })(data);

console.log(result);
// => [ 'subNav0', 'subNav1', 'subNav2', 'subNav3', 'subNav4', 'subNav5' ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09f929a959384dd8393919eb0c1c4dec0dec0">[email protected]</a>"></script>

Disclaimer: I'm the creator of object-scan

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

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

What is the best way to iteratively fade in data from a MySQL database one by one?

How can I load data from a MySQL database and display it one by one with a fade-in effect? Let's say I have a total of 40 images stored in the database. First, I want to display each image like this: <li class="img" style=" list-style: none; flo ...

Insert DOM elements at the start of the parent element

I'm currently using the following JavaScript code to insert AJAX responses into a div with an ID of results: document.getElementById("results").innerHTML=xmlhttp.responseText; The issue I am encountering is that this code adds all new elements after ...

Incorporating base Tailwind CSS colors with the daisyUI theme: A simple guide

For my NextJS project, I'm utilizing Tailwind CSS in conjunction with daisyUI. In my configuration file tailwind.config.js, I have it set up as follows: /** @type {import('tailwindcss').Config} */ /* eslint-env node */ module.exports = { ...

Is it possible to customize the font color of a placeholder in a v-text-field component in Vue?

Recently, I added the following code snippet to my project: <v-text-field hide-details class="search-field" id="name-input" placeholder="Search by name" v-model="search"></v-text-field> I wanted to change the font color of the placeholder tex ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

What is the method for selecting a specific row in a Primefaces Datatable using HtmlUnitDriver and Selenium?

Check out this code snippet: import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriv ...

Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS. I have an index.html file, along with controllers and partials. The <body> tag is located in the index.html. I am trying to set the class for the body using my controller. After adding a value to $scope.body_c ...

Struggling to establish a consistent header on every page in AngularJS

I've been attempting to implement a header that appears on all my pages using AngularJS. Here is the current setup I have: In my HTML file, I've included the following code: <html ng-app="webApp"> <script src="/vendor/angular.min.js"& ...

How should one correctly trigger an event in Google scripts?

When it comes to calling in the active elements, I have been using event.source.getActive and SpreadsheetApp.getActive. However, I have noticed that I sometimes interchange them in my script and face issues. So, I am unsure about which method is more app ...

Retrieve particular information from a JSON array using jQuery and PHP

I need to extract specific information from a JSON file hosted at a given URL and store that data in a PHP variable. The JSON data is fetched from the following URL: Here's an example of the JSON content: { "viducius": { "id": 26541044, ...

Escaping latitude and longitude coordinates using PHP

I am looking to include longitude and latitude values in a json file. However, the current code I have escapes the values and adds quotation marks. Example of json output{"votes":["{\"lat\":\"51.426799\",\"lng\":\"-0.331 ...

How can I access dynamically created input elements without using $refs, such as getting focus?

Is there a way to handle dynamically created inputs for editing purposes without using jQuery or vanilla JS all the time? Each input element has its own ID and is displayed through v-if when editing is triggered. However, Vue does not recognize them in r ...

Error: Definitions missing during conversion from JSON to XML

I've scoured the internet extensively, but I still can't figure out why... The header file Newtonsoft.Json.Jsonconvert is missing the definition for DeserializeXmlNode(), which I need to convert Json to Xml. Additionally, the load() function do ...

The issue of data binding not refreshing in vue 2.3 with AJAX requests

Following a successful AJAX request, there is an issue with the updated data not displaying on the page. Instead, it remains empty or null. There seems to be a disconnect between the data returned as a front-end variable and the dynamically rendered HTML ...

Learn how to create a "generated" texture coordinate in three.js similar to how it is done in Blender Cycles

How can I properly display a texture on a cylinder object using THREE.js without distortion? Currently, the texture appears stretched along the edges of the cylinder as shown here: https://i.sstatic.net/O2YFr.png This issue is based on the texture provide ...

Searching and updating data in a table using DataTables and conditional statements

Is there a way to perform a find/replace on specific elements within a datatable? My goal is to replace certain elements in the table with font awesome icons: Here is the JavaScript code I am using: $(document).ready(function() { $('#example' ...

Choosing an option from an HTML dropdown menu within an Android WebView

Can someone provide me with an example of how to use JavaScript to select an item from an HTML drop-down menu after downloading a webpage to WebView? ...

Steps to transfer the content of a label when the onclick event occurs

Seeking advice on how to send the dynamically varying value of a label upon clicking an anchor tag. Can anyone recommend the best approach to passing the label value to a JavaScript function when the anchor is clicked? Here is a sample code snippet: < ...