Discovering a specific element within a deeply nested JavaScript object

let data = [{
    "ItemAID" : 1,
    "ItemADesc" : [ {
      "ItemBid" : 11,
      "ItemBDesc" : [ {
        "ItemCid" : 111,
        "ItemCTitle" : "TitleC111",
      }, {
        "ItemCid" :112,
        "ItemCTitle" : "TitleC112",
      } ]
    }]},

    {
        "ItemAID" : 2,
        "ItemADesc" : [ {
          "ItemBid" : 21,
          "ItemBDesc" : [ {
            "ItemCid" : 211,
            "ItemCTitle" : "TitleC211",
          }, {
            "ItemCid" :212,
            "ItemCTitle" : "TitleC212",
          } ]
        }]}]
console.log(data.find(A => A.ItemADesc.find(B => B.ItemBDesc.find(C=>C.ItemCid === 212)?.ItemCTitle)));

I want to retrieve the value of ItemCTitle when the itemCid matches a specific ID. The current code returns the entire object with matching itemCid, instead of just the nested variable value. Any help will be highly appreciated.

Answer №1

With the use of Array.reduce, it becomes possible to extract only the array of ItemC and easily locate the desired item within that array.

let input = [{
  "ItemAID" : 1,
  "ItemADesc" : [ {
    "ItemBid" : 11,
    "ItemBDesc" : [ {
      "ItemCid" : 111,
      "ItemCTitle" : "TitleC111",
    }, {
      "ItemCid" :112,
      "ItemCTitle" : "TitleC112",
    } ]
  }]},

  {
      "ItemAID" : 2,
      "ItemADesc" : [ {
        "ItemBid" : 21,
        "ItemBDesc" : [ {
          "ItemCid" : 211,
          "ItemCTitle" : "TitleC211",
        }, {
          "ItemCid" :212,
          "ItemCTitle" : "TitleC212",
        } ]
      }]}];

const itemC = input.reduce((acc, cur) => {
  if (cur['ItemADesc'] && cur['ItemADesc'].length > 0) {
    cur['ItemADesc'].forEach(({ ItemBDesc }) => {
      if (ItemBDesc.length > 0) {
        acc.push(...ItemBDesc);
      }
    });
  }
  return acc;
}, []).find(({ ItemCid }) => ItemCid === 211);

console.log(itemC.ItemCTitle);

Answer №2

If you're in need of locating deeply buried objects, consider utilizing the library known as d-forest.

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

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Can the ASP.NET MVC 3 route constraints be modified to return a 400 Bad Request with JSON responses instead?

Currently, I am working on developing REST resources with the ASP.NET MVC 3 framework. So far, my experience has been positive as I enjoy the flexibility that MVC 3 offers and find it easy to create REST services. However, I have encountered difficulties w ...

What is the best way to create separate positions for items within a single div?

https://i.sstatic.net/FQRY4.jpgAfter looping through various names and accessing them from a single div using {{item}}, I encountered an issue. All the names are within one parent element. This is the code snippet: <div :style="image" cl ...

Regular expressions to extract JSON data

In my file xyz.json, there is a JSON structure like this: {"number1":2.0,"number2":7.5,"date":"2020-05-12T08:45:00.000Z","info":[],"text":{"text1":{"text11":3,"text12" ...

Endless cycle plaguing Grunt tasks

Currently in the process of setting up a foundation Gruntfile.js for some upcoming projects. Recently started working on a new computer, so I had to rebuild everything from scratch. Used Homebrew to install Node and NPM, followed by installing Grunt global ...

Refresh a DIV using two SQL queries in forms

I am encountering an issue with updating a single div element using the results from two different forms on an HTML page. I want either form1 or form2 to display results in the same div element, and it should be updated with one line of content fetched fro ...

How to delete a specific element from the DOM using its ID in JavaScript

I am facing a challenge in removing an element from the page dynamically without refreshing using JavaScript. The script I have written successfully deletes the record from the database, but I need assistance in removing the container element based on it ...

Accessing JSON values using JQuery

When I receive a response from a processor, it is structured like this. When I log the data, here is what I see: { "status":"No", "errors":["Dummy Error msg 1","Dummy Error msg 2"], "successMessages":["Dummy Success msg 1","Dummy Success msg 2"] } It& ...

Manipulating Python lists

What is the reason behind the output of 8 from this code snippet? lst = [1, 1, 2, 3, 5, 8, 13] print(lst[lst[4]]) Output: 8 ...

How to efficiently retrieve data from a JSON file stored on an SD Card and showcase the information on a textview using Android?

I have a text file stored in my SdCard and I want to parse it using a Json parser. Once parsed, I would like to display the data in my textview. How can I achieve this? { "data": [ { "id": "1", "title": "Farhan Shah", "duration ...

Steps to send an array through the $_POST array using form.serialize() in ajax

How can I send an array within the $_POST array using AJAX with form data like this: array('name'=>'test','accom'=>array(0=>'test2'.1=>'test3')): $.ajax({ url : 'add_ ...

Building a Database in a Node.js Express Application Using Jade and JavaScript

UPDATE After conducting extensive research, I have discovered that the web application utilizes the node-db-migrate package. Within the migration folder, there are two migrations containing table creations. As I recently git cloned the project, it is evid ...

How can I retrieve the value of a specific JSON attribute in Cloud Functions?

Inside the text box for my pubsub message, there is a json file that appears like this: { "message": "Good morning", "sender": "Joe Schmoe" } I've made several attempts to retrieve the value of "sender", but have been unsuccessful in the following w ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

How can Vue detect modifications made in the edited field?

I am facing an issue with tracking changes in a specific object. Here is the structure of the object: users: { email: '', password: '' } My goal is to detect any edits made to the keys within the users object and store the key ...

The HTML Style for implementing HighChart title text does not work when exporting files

I have inserted the <br/> and &nbsp; HTML tags into the HighChart titles. The style changes successfully appear in the chart view, but unfortunately, when exported as PNG or JPEG images, the text style fails to apply in the resulting images. To s ...

Encountering issues with creating a session in Selenium/webdriver while utilizing Safari 12

Ever since making the update to Safari 12, my automated scripts have been encountering a new error: SessionNotCreatedError: Request body does not contain required parameter 'capabilities'. (Interestingly, this error is exclusive to Safari and d ...

I keep encountering the error message "ReferenceError: window is not defined" in Next.js whenever I refresh the page with Agora imported. Can someone explain why this is happening?

Whenever I refresh my Next.js page with Agora SDK imported, I keep encountering the error "ReferenceError: window is not defined". It seems like the issue is related to the Agora import. I attempted to use next/dynamic for non-SSR imports but ended up with ...

When the 'keyup' event is detected, trigger the function only on keyup

Looking for assistance in setting this to only trigger on keyup events. Can anyone provide guidance? $(function() { $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() { $('#link-headline-fb').text($( ...

Save the test outcomes in HTML format using cypress

Can Cypress test results be exported to an HTML or another format, similar to cucumber-report.html? ...