Acquiring mapping information through JSON data retrieval

Overview :

Each levelNum has three corresponding dropdowns. For example, the dropdown for levelNum2 includes

(Department-Unit-1, Department-Unit-2 & Department-Unit-3)
, levelNum3 includes
(Division-Unit-1 & Division-Unit-2)
, and levelNum4 includes
(Business-Unit-1 & Business-Unit-2)
.

An array of objects is present. Each object contains a property named hierarchyLevels which is an array of objects. These nested objects have two properties: unitName & levelNum. This structure is represented in the below JSON:

var data = [{
    "hierarchyLevels": [{
        "unitName": "Department-Unit-3",
        "levelNum": 2
    }, {
        "unitName": "Division-Unit-2",
        "levelNum": 3
    }, {
        "unitName": "Business-Unit-1",
        "levelNum": 4
    }]
}, {
    "hierarchyLevels": [{
        "unitName": "Department-Unit-1",
        "levelNum": 2
    }, {
        "unitName": "Division-Unit-1",
        "levelNum": 3
    }, {
        "unitName": "Business-Unit-2",
        "levelNum": 4
    }]
}, {
    "hierarchyLevels": [{
        "unitName": "Department-Unit-2",
        "levelNum": 2
    }, {
        "unitName": "Business-Unit-1",
        "levelNum": 4
    }]
}]

Approach Taken :

function getMultipleObjectFromList(propertyName, value, list){
    return list.filter(function (item) {
        return item.hierarchyLevels.some(function (level) {
            return level[propertyName] === value;
        });
    });
};

var res = getMultipleObjectFromList('unitName','Business-Unit-1',data);

Goal :

I aim to automatically populate lower level dropdowns with associated unitName when selecting a specific unitName from a higher level dropdown. For instance, choosing Business-Unit-1 from the levelNum4 dropdown should update the other dropdowns accordingly. In this case, levelNum3 will show only Division-Unit-2 and levelNum2 will display

(Department-Unit-2 & Department-Unit-3)
.

Answer №1

The data structure you are working with contains more levels than what your function currently handles. Specifically, there is a property called hierarchyLevels which is an array that you are not iterating over.

Below, I have provided an updated function that retrieves the hierarchyLevels that match a certain criteria. Additionally, there is another function included that returns the inner object when a match is found instead of the entire hierarchyLevels array. This can be useful for populating drop-down menus:

function extractObjects(propertyName, value, list){
    return list.filter(function (item) {
        return item.hierarchyLevels.some(function (level) {
            return level[propertyName] === value;
        });
    });
};

function getDetailFromList(propertyName, value, list){
    return list.map(function (item) {
        return item.hierarchyLevels.filter(function (level) {
            return level[propertyName] === value;
        }).pop(); // only return single match
    }).filter(function (item) { // exclude null
        return item;
    }); 
};


var data = [{
    "hierarchyLevels": [{
        "unitName": "Department-Unit-3",
        "levelNum": 2
    }, {
        "unitName": "Division-Unit-2",
        "levelNum": 3
    }, {
        "unitName": "Business-Unit-1",
        "levelNum": 4
    }]
}, {
    "hierarchyLevels": [{
        "unitName": "Department-Unit-1",
        "levelNum": 2
    }, {
        "unitName": "Division-Unit-1",
        "levelNum": 3
    }, {
        "unitName": "Business-Unit-2",
        "levelNum": 4
    }]
}, {
    "hierarchyLevels": [{
        "unitName": "Department-Unit-2",
        "levelNum": 2
    }, {
        "unitName": "Business-Unit-1",
        "levelNum": 4
    }]
}];

var matchingResults = extractObjects('unitName','Business-Unit-1',data);

var level2Data = getDetailFromList('levelNum', 2, matchingResults);

var level3Data = getDetailFromList('levelNum', 3, matchingResults);

var outputContent = '<h2>Matching Data:</h2>' + JSON.stringify(matchingResults, null, 4) + '\n'
           + '<h2>Level 2 Results:</h2>' + JSON.stringify(level2Data, null, 4)  + '\n'
           + '<h2>Level 3 Results:</h2>' + JSON.stringify(level3Data, null, 4);

document.querySelector('pre').innerHTML = outputContent;
<pre></pre>

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

What is the method to activate map dragging in Leaflet only while the spacebar is pressed?

When using Leaflet maps, the default behavior is to drag the view around by only clicking the mouse. However, I am interested in enabling dragging with the mouse only if the spacebar is pressed as well. I would like to reserve mouse dragging without the sp ...

Having issues with Facebook's login API for JavaScript?

Apologies for the improper formatting. I am encountering errors in my JavaScript compiler while working with the Facebook Login API... Error: Invalid App Id - Must be a number or numeric string representing the application id." all.js:53 "FB.getL ...

How to rename a class of an image tag using jQuery

I need to update the class name in my image tag <img src="img/nex2.jpeg" class="name"> When hovering over with jquery, I want to add a new class to it. After hovering, the tag should appear as follows: <img src="img/nex2.jpeg" class="name seco ...

Creating a welcome screen that is displayed only the first time the app is opened

Within my application, I envisioned a startup/welcome page that users would encounter when the app is launched. They could then proceed by clicking a button to navigate to the login screen and continue using the app. Subsequently, each time the user revisi ...

I must adjust the size of images based on the size of the viewer's screen

Hello everyone, I could really use some assistance as I am not an expert programmer but just a site admin. My issue is this: I have a website running on PHP and I want to display images to my members while keeping them within specific size limits so they ...

Generating JSON data with Ruby for a collection of items

I'm a beginner with Ruby. My goal is to generate a JSON file for a set of elements. To achieve this, I am utilizing the each function to fetch the data. The desired structure of the JSON file for a 4 element array is as follows: '{ "desc" ...

Has the web application continued to run in the background even after toggling between tabs on the browser?

Does the app continue running in the background even when I'm not on that specific tab? Or does it pause when I switch between tabs, requiring a new request to the server for any updated data from the database upon returning to that tab? Edit: Curren ...

How can we use JavaScript to add a class to the <html> element?

What is the method to apply a class to the root element <html> in JavaScript? ...

Disabling a DropDownList in ASP MVC when a checkbox is marked: A step-by-step guide

Currently, I am in the process of developing an application using ASP .Net MVC 3 with C# and SQL Server 2005. Additionally, I am incorporating Entity Framework along with the Code First Method for this project Within a specific view, there are 2 checkbox ...

Converting CSV to nested JSON up to three levels deep using Python

Here is the CSV data I am currently working with: id,category,sub_category,sub_category_type,count 0,fruits,citrus,lemon,30 1,fruits,citrus,lemon,40 2,fruits,citrus,lemon,50 3,fruits,citrus,grapefruit,20 4,fruits,citrus,orange,40 5,fruits,citrus,orange,10 ...

Sending requests through RoR and receiving JSON responses - what's next?

Hey there! So I'm diving into the world of Ruby on Rails and I've managed to create a form that sends data to an external widget which then returns JSON. Here's what my form looks like: <%= form_for :email, :url => 'http://XXX.X ...

When a Vue.js datepicker is set as required, it can be submitted even if

When using the vuejs-datepicker, setting the html required attribute on input fields may not work as expected. This can lead to the form being submitted without an input value. <form> <datepicker placeholder="Select Date" required></datep ...

Could someone assist me in identifying the error or mistake?

For my project, I have implemented client and server sign-in & sign-up functionalities. However, after fetching the register API from the frontend, it is displaying an error message "please fill all fields" even though I have provided validation for al ...

Should I install @capacitor/android as a dev dependency in the package.json file of a React project?

I was pondering whether it would be better to add @capacitor/android, @capacitor/ios, and @capacitor/core as development dependencies. ...

What is the best way to display a list of items in Vue JS while maintaining the

Looking to display my Vue.js list in reverse order using v-for without altering the original object. The default HTML list displays from top to bottom, but I want to append items from bottom to top on the DOM. Telegram web messages list achieves this wit ...

What could be causing Next.js middleware to run repeatedly?

Recently, I set up a brand new Next.js project using npx create-next-app@latest --typescript. Upon completing the installation (version 13.3.4), without making any modifications to existing files, I introduced a new file named middleware.ts within the src ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

What should we do to resolve the uncommon use of the 'this' es-lint error? Which rule should we disable?

Recently, I encountered an issue with my Nuxt setup that is configured with el-lint and prettier. Every time I try to use 'this' within my template, it throws up an error unexpectedly. 6:15 error Unexpected usage of 'this' vue/this ...

When attempting to push `content[i]` into an array in AngularJS, it is flagged

In my JSON data, I have the following structure: var data = [{ id: 1, name: 'mobile', parentid: 0, limit:3 }, { id: 2, name: 'samsung', parentid: 1 }, { id: 3, name: 'moto', parenti ...

Creating a JSON file using the attributes and values of HTML tags

I am seeking assistance in generating a JSON file from HTML data using jQuery. The HTML structure consists of multiple departments with similar tags and classes: <div class="department_one"> <h1>Name Of Manufacturer</h1> < ...