Retrieve a data value from a JSON object by checking if the ID exists within a nested object

I am facing the challenge of navigating through a JSON object where child objects contain IDs that need to be matched with parent properties. The JSON structure looks like this:

{
    id: 1,
    map: "test",
    parameter_definitions: [{ID: 1, parameterUnits: "%"},{ID: 2, parameterUnits: "%"}],
},
{
    id: 2,
        map: "test2",
    parameter_definitions: [{ID: 3, parameterUnits: "%"},{ID: 4, parameterUnits: "%"}],
}

My goal is to extract the 'map' value from the correct JSON object based on whether a given ID exists within the parameter_definitions array. This task seems challenging and I am struggling to find a solution.

Answer №1

If you're looking for a way to retrieve map elements by ID, check out this function called "getMapElementById":

  let maps = [{
                 id: 1,
                 map: "test",
                 parameter_definitions: [{ID: 1, parameterUnits: "%"},{ID: 2, parameterUnits: "%"}],
                },
                {
                  id: 2,
                  map: "test2",
                  parameter_definitions: [{ID: 3, parameterUnits: "%"},{ID: 4, parameterUnits: "%"}],
                 }]


    function getMapElementById( maps, requiredId ) {

          for(let i=0;i<maps.length;i++){
              for(let j=0;j<maps[i].parameter_definitions.length;j++){
                  if( maps[i].parameter_definitions[j].ID == requiredId ) {
                     return maps[i];
                  }
              }
          }

    }

    let mapResult = getMapElementById(maps, 3);
    console.log(mapResult);

Answer №2

It's not definitively stated whether multiple parent objects are allowed to have children objects with the same ID, but you can handle this scenario by employing a combination of filter and find methods:

const objects = [
    {
        id: 1,
        map: "test",
        parameter_definitions: [{ ID: 1, parameterUnits: "%" }, { ID: 2, parameterUnits: "%" }],
    },
    {
        id: 2,
        map: "test2",
        parameter_definitions: [{ ID: 3, parameterUnits: "%" }, { ID: 4, parameterUnits: "%" }],
    }
];

const filteredObjects = objects.filter(object => object.parameter_definitions.find(param => param.ID === 2));
if (filteredObjects.length > 0) {
  // If it is guaranteed that only one parent object matches each child object ID, simply return the first item from the array
  console.log(filteredObjects[0].map);

  // If multiple parent objects can have the same child object ID, utilize the map function to access the map property of all parent objects
  console.log(filteredObjects.map(object => object.map));
}

Answer №3

We apologize, but your question seems a bit unclear. Are you searching for this information?

// Sample code snippet

const myData = [{ id: 1, map: 'test', parameter_definitions: [{ ID: 1, parameterUnits: '%' }, { ID: 2, parameterUnits: '%' }] }, { id: 2, map: 'test2', parameter_definitions: [{ ID: 3, parameterUnits: '%' }, { ID: 4, parameterUnits: '%' }] }];

const getRootElement = (data, id) => objectScan(['[*].parameter_definitions[*].ID'], {
  abort: true,
  filterFn: ({ value, parents, context }) => {
    if (value === id) {
      context.push(...parents);
      return true;
    }
    return false;
  }
})(data, [])[2];

console.log(getRootElement(myData, 5));
// => undefined

console.log(getRootElement(myData, 3));
// => { id: 2, map: 'test2', parameter_definitions: [ { ID: 3, parameterUnits: '%' }, { ID: 4, parameterUnits: '%' } ] }
.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="e28d8088878196cf9181838ca2d3d1ccdaccd2">[email protected]</a>"></script>

Important Note: The individual who created object-scan is the author.

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

Placing content retrieved from a MySQL database within a form displayed in a ColorBox

Having difficulty inserting text from a MySQL database into a form (textfield) inside a ColorBox. The current script is as follows: <a href="#" class="bttn sgreen quote1">Quote</a> var postQuote[<?php echo 4id; ?>]=<?php echo $f ...

How can I simulate a callback function that was not tested?

Currently experimenting with the method below: startScriptLoad(): void { const documentDefaultView = this.getDocumentDefaultView(); if (documentDefaultView) { const twitterData: ICourseContentElementEmbedTweetWidgetData = this.getTwitterWid ...

The MUI persistent drawer navigation bar becomes dysfunctional when accessing a specific route

Exploring the MUI library for the first time, I successfully created a navigation bar that functions properly for one route (Dashboard). However, when attempting to implement it on the candidate route, it collapses as shown in this Screengrab of collapsed ...

Disable the button until all input fields contain text in ASP

Curious if anyone knows how to disable a button until all text boxes have input in ASP.NET and C#. Here is an image showing the scenario I'm referring to - wanting to gray out the commit button. Thanks, Chris! ...

Trouble keeping HTML/Javascript/CSS Collapsible Menu closed after refreshing the page

My issue is that the collapsible menu I have created does not remain closed when the page is refreshed. Upon reloading the page, the collapsible menu is always fully expanded, even if it was collapsed before the refresh. This creates a problem as there is ...

Interacting with server-side data using JQuery's $.ajax method and handling JSON

The JSON response returned from the request is not being recognized. request = $.ajax({ url: "form_handler.php", type: "post", dataType: "json", data: serializedData }); The PHP code within form_handler.php that generates ...

Access JSON data from PHP server and display it in a listview on an Android platform

I have successfully developed a web service and now I am looking to retrieve the JSON object in order to populate data into an Android list view. Below is my PHP code snippet: $sql_query="SELECT * FROM testtable"; $query=mysqli_query($con,$sql_query); $ro ...

There was an issue with the origin null not being permitted by Access-Control-Allow-Origin

Possible Duplicate: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin I am currently working on a weather application that runs smoothly in browsers. However, when I try to deploy it on my Android phone, it encounters iss ...

Converting JSON data to a pandas DataFrame requires the list indices to be integers

I have a large JSON dataset that I want to convert to CSV for analysis purposes. However, when using json_normalize to build the table, I encounter the following error: Traceback (most recent call last): File "/Users/Home/Downloads/JSONtoCSV/easybill.py" ...

What are some techniques for utilizing jq to extract a specific field from a terraform blueprint in order to display the resources that have been modified or updated?

Is there a way to get a quick summary of changes in a Terraform plan instead of the detailed output? I believe it can be achieved with Terraform plan and jq. Here's what I have tried: To generate a plan, I use this command: terraform plan -out=tfpl ...

If the width of the table is set to 100% in the CSS, the legend in the Flot chart will automatically shift to the

When the CSS for the table is set to { width:100%}, the Flot chart's legend moves to the left side. Is there any way to maintain the table { width:100%} while also preventing this shift, considering that the CSS is applied site-wide? Here is a jsfid ...

Is there a method to instruct POSTMAN to continuously transmit JSON files to my application?

Currently, I am working on an application in .NET core which includes a method that receives a request with JSON data, deserializes it, and saves the information. My goal is to use Postman to send a JSON file containing multiple objects one by one to my ...

Tips for parsing a JSON object efficiently

Javascript var obj = { "name" : ["alex","bob","ajhoge"], "age" : [30,31,33] }; To display the value "alex," you can use: document.write(obj["name"][0]) But how can we filter through 'obj' to retrieve all data like this? html <ul ...

How can I alter the div once the form has been submitted?

Is there a way to change the background of a form and its results after submitting the form? I need to switch the image background to a plain color. I attempted to use a solution I found, but it doesn't seem to be working as expected. You can view my ...

Encountering issues with running an AngularJS application (version 1.6) in Visual Studio following the activation of script

I am new to working on an angular 1.6 application and still learning the ropes. The project consists of an asp.net web api project that needs to be run before starting the angular project. Everything was running smoothly until I tried to debug a parameter ...

Inserting additional information and assigning a category following a prosperous AJAX request accompanied by output from php echo

I'm currently working on implementing an AJAX call to my PHP file to send an email once a contact form is submitted. Initially, I had everything functioning properly where the response from PHP was displayed in a div above the form. However, I wanted ...

Integration of Angular.js functionalities within a Node.js application

After working on my node.js app for a few weeks, I decided to add some additional features like infinite-scroll. To implement this, I needed to use packages in node.js along with angular.js. So, I decided to introduce angular.js support to the app, specifi ...

Mastering the art of iterating through arrays using node.js request()

After transitioning from passing single values to multiple values in my node API, I encountered an issue where the API no longer responded. Here is an example of single values for fields: tracking: "123", // Only one tracking number carrier: "usps" // On ...

Convert a Treeview to JSON format and then convert it back to a Treeview through des

I want to convert a Treeview node into JSON format and then back into a Treeview. Within my code, I have a unique SubNode class that looks like this: Class SubNode: TreeNode { dynamic obj; } Essentially, every tree node will contain ...

Using JavaScript to pass a newly created variable as an argument in a default

Currently, I am developing a node application that heavily utilizes promises. To enhance the readability of my code, I have been removing anonymous functions and storing them in a JavaScript object called "myCallbacks". Here's an example: let myCallb ...