Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data:

[
            {
                "name": "India",
                "children": [
                    {
                        "name": "Delhi",
                        "children": [
                            {
                                "name": "South Delhi"
                            },
                            {
                                "name": "North Delhi"
                            }
                        ]
                    },
                    {
                        "name": "Tamil Nadu",
                        "children": [
                            {
                                "name": "Chennai"
                            },
                            {
                                "name": "Coimbatore"
                            }
                        ]
                    }
                ]
            },
            {
                "name": "America",
                "chilren": [
                    {
                        "name": "California",
                        "children": [
                            {
                                "name": "Trinity"
                            },
                            {
                                "name": "Yolo"
                            }
                        ]
                    },
                    {
                        "name": "Florida",
                        "children": [
                            {
                                "name": "Bradford"
                            },
                            {
                                "name": "Calhoun"
                            }
                        ]
                    }
                ]
            }
        ]
    

In the JSON data above, if I search for the name "Yolo", I expect the result to be America -> California -> Yolo. Can anyone assist me with this?

Below is the code snippet I have written. It currently only displays the child, but I need to also show the parent.

searchRecursive(value) {
            for (var i = 0; i < value.length; i++) {
                let lowerCaseName = value[i]['name'].toLowerCase();
                if (lowerCaseName.includes('yolo')) {
                    this.searchedItems.push(value[i]);
                } else if (value[i]['children']) {
                    if (value[i]['children'].length > 0) {
                        this.searchRecursive(value[i]['children']);
                    }
                }
            }

            return this.searchedItems;
        }
    

Answer №1

After analyzing the array provided, one possible solution could involve the following code:

const targetLocation = 'Yolo';

const result = countries.reduce((acc, val) => {
  const city = val.children[0].children.find(city => city.name === targetLocation);
  const country = val.name;
  const state = val.children[0].name;

  if (city) {
    return {
      country,
      state,
      city: city.name
    };
  }
});

The resulting object stored in the variable `result` would be:

{ country: 'America', state: 'California', city: 'Yolo' }

Answer №2

This code snippet is a versatile solution that can be applied to any city:

let search = "Chennai";

    const transform = (dArray, parent) => {     
    return dArray.map(item => [item.children, item.name, parent]);
    }

    transformed = [].concat.apply([], (data.map(country => transform(country.children,country.name))));
    transformed2 = [].concat.apply([], (transformed.map(item => transform(item[0], item[1]))));

    query1 = transformed2.filter(item => item[1] === search); 
    query2 = transformed.filter(item => item[1] === query1[0][2])

   console.log(query2[0][2] + ' -> ' + query1[0][2] + ' -> ' + query1[0][1])

Though not the most elegant, this script effectively transforms the data into two structured arrays.

Transformed Array 1:

(4) [Array(3), Array(3), Array(3), Array(3)]
0: (3) [Array(2), "Delhi", "India"]
1: (3) [Array(2), "Tamil Nadu", "India"]
2: (3) [Array(2), "California", "America"]
3: (3) [Array(2), "Florida", "America"]
length: 4
__proto__: Array(0)

Transformed Array 2:

(8) [Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3)]
0: (3) [undefined, "South Delhi", "Delhi"]
1: (3) [undefined, "North Delhi", "Delhi"]
2: (3) [undefined, "Chennai", "Tamil Nadu"]
3: (3) [undefined, "Coimbatore", "Tamil Nadu"]
4: (3) [undefined, "Trinity", "California"]
5: (3) [undefined, "Yolo", "California"]
6: (3) [undefined, "Bradford", "Florida"]
7: (3) [undefined, "Calhoun", "Florida"]
length: 8
__proto__: Array(0)

The next step involves merging these structures using .filter functions. It's important for town names to be unique in order for the solution to work correctly.

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

Surprising Logging Quirks in Angular

I've encountered a perplexing issue in my Angular app where an array is logged before adding an element to it, yet the log shows the updated array with the added element. This array is then utilized in an HTML file with ngFor. component.ts file inter ...

"Learn how to securely redirect to a custom URI scheme with a fail-safe option to display alternative content if not supported

In short: Can a visitor be redirected to a custom URI scheme or shown alternate content if the scheme is not supported? My specific scenario involves developing a mobile app that utilizes a custom URI scheme for users to invite others to actions within th ...

Avian-themed masking feature for jCarousel

Currently, I have a series of images in constant motion using jCarousel. Only one image is visible fully at any given time, and I am looking to create a "feathering" effect on the edges of the carousel so that the images smoothly fade in and out as they co ...

Establishing header cache control within the KOA framework

I'm currently working on an app that is using the KOA framework, and I am struggling to understand why a specific page is being cached. Even after attempting a hard reload in all browsers, the changes do not appear unless the cache is cleared. I woul ...

Having issues with incorporating a component into another component in VueJS

Having spent approximately 30 hours on diving into VueJS, I am encountering some difficulties when it comes to using a component within another component. Seeking assistance from someone knowledgeable in this area to provide me with some clarification. Pr ...

Enhancing the appearance of list options in Autocomplete Material UI by utilizing the renderOption feature

I'm putting in a lot of effort to customize the option elements in the autocomplete list. My plan is to achieve this using the renderOptions prop, where I can create DOM elements and easily apply styles with sx or styled components. However, somethin ...

Combining multiple pipe collections in a single Gulp task for both CoffeeScript and JavaScript files

I've been working on creating a single scripts task that can handle both .coffee and .js files effectively: Coffee files need to go through coffee(), coffeelint() and coffeelint.reporter() JS files should run through jshint() All files then need to ...

Tips for locating the .owl-video-frame class using jQuery in Owl Carousel 2

In my carousel, I have multiple videos displayed as follows: <div id="owl4" class="owl-carousel owl-theme"> <div class="owl-item-container video-aspect-16-9" data-aspect="1.7777778"> <a class="owl-video" href ...

Transferring information to modal without using AngularUI

I'm currently working on an Angular application and facing an issue with passing data from my controller to a modal. Here is the HTML code on my index page: <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> ... </head> & ...

In Angular, the object may be null

click here for image Encountering an error message stating that Object is possibly 'null' when utilizing querySelector and addEventListener in Angular. ...

Guide to triggering an Observable depending on the result of a different Observable and obtaining an Observable as output

Looking to implement a service method in Angular 10 that returns an Observable for a custom User object. The goal is to have a service method that checks if the main service is running, and if not, return data from a local resource as an alternative. Pseu ...

Is there a way to incorporate the req.setHeaders method with the res.redirect method in the same app.get function?

var express = require('express'); var app = express(); var PORT = process.env.PORT; app.get('/', function(req, res){ res.json('To search for images, enter your query parameters like this: https://api.cognitive.microsoft.com/bi ...

How to use RegExp to locate the final return statement within a JavaScript code string

Take a look at this code snippet: cont x = 10; function foo() { return x; // ;; end of function ;; // /* here is a some text here too */ } function bar() { return 10 } return foo() + bar(); // ;;done;; // /* yolo yolo */ This string cont ...

javascript, issues with floating and displaying elements

I am currently working on creating a JavaScript menu that has a click function to smoothly slide up and down. Although the JavaScript code appears to be functioning correctly, it seems that there is some interference with the CSS. Despite attempting vario ...

Include the name of the uploaded attachment in the textarea before hitting the submit button

Is there a way to automatically insert the filename into a textarea before the user submits the form? Can this be achieved using PHP or JavaScript? Thank you. <form id="Apply" name="Apply" method="post" enctype="multipart/form-data" action="applyLea ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

Sometimes, JQuery struggles to set input values accurately

Exploring the single page app sample provided here, I have encountered some anomalies when attempting to manipulate input controls with JQuery under certain conditions. Below is the consistent HTML structure followed by the JavaScript snippets in question. ...

Here's a guide on how to display texts underneath icons in Buttons using Material UI

Currently, this is the Button I have displayed I am trying to figure out how to position the Dummy Button text beneath the icon. Can someone assist me with this? Below is my code snippet: <Button className={classes.dummyButton}> <Image src ...

What is the most effective method to patiently anticipate a specific duration for a function's output?

I am faced with a situation where I have two functions at hand. One function performs complex logic, while the other wraps this function to provide either the result of computation or an error message after a specified amount of time t. Consider the follo ...