What is the best way to locate a specific item within an array of objects, especially when each object has the potential to contain an array of objects of the

I am grappling with the challenge of finding a specific object within an array of objects, where the desired object may be nested within another array of one of the objects.

I have experimented with various iterations of forEach loops and recursion methods.

{
    "id": 1,
    "messages": [{
            "id": 4,
            "message": "XXXXXXXX",
            "code": "XXXXXX",
            "subMessages": null
        }, {
            "id": 8,
            "message": "XXXXXXXX",
            "code": "XXXXXX",
            "subMessages": [{
                    "id": 9,
                    "message": "XXXXXXXX",
                    "code": "XXXXXX",
                    "subMessages": null
                }
            ]
        }, {
            "id": 10,
            "message": "XXXXXXXX",
            "code": "XXXXXX",
            "subMessages": [{
                    "id": 11,
                    "message": "XXXXXXXX",
                    "code": "XXXXXX",
                    "subMessages": [{
                            "id": 12,
                            "message": "XXXXXXXX",
                            "code": "XXXXXX",
                            "subMessages": null
                        }
                    ]
                }
            ]
        }
    ]
}

The depth of nesting is uncertain and may exceed that shown in the example, and the arrays may contain multiple messages each. My objective is to locate a message based on its unique ID (IDs are unique across all messages).

Any suggestions?

Answer №1

Based on your explanation, it seems like your goal is to retrieve the message associated with a specific id.

If you require the entire message object, you can modify the line of code from `returnData = messageObj.message;` to `returnData = messageObj;`

I opted for using array.some instead of a for loop to accomplish this task

var messagesData = {
  "id": 1,
  "messages": [{
    "id": 4,
    "message": "4XXXXXXXX",
    "code": "XXXXXX",
    "subMessages": null
  }, {
    "id": 8,
    "message": "8XXXXXXXX",
    "code": "XXXXXX",
    "subMessages": [{
      "id": 9,
      "message": "9XXXXXXXX",
      "code": "XXXXXX",
      "subMessages": null
    }]
  }, {
    "id": 10,
    "message": "10XXXXXXXX",
    "code": "XXXXXX",
    "subMessages": [{
      "id": 11,
      "message": "11XXXXXXXX",
      "code": "XXXXXX",
      "subMessages": [{
        "id": 12,
        "message": "12XXXXXXXX",
        "code": "XXXXXX",
        "subMessages": null
      }]
    }]
  }]
};


function getMessageById(id) {
  var returnData;

  function searchForMessage(messages) {
    messages.some(function(messageObj) {
      if (messageObj.id === id) {
        returnData = messageObj.message;
        return true;
      } else if (messageObj.subMessages && messageObj.subMessages.length) {
        return searchForMessage(messageObj.subMessages);
      } else {
        return false;
      }
    });
  }
  searchForMessage(messagesData.messages);
  return returnData;
}

console.log(getMessageById(11));
console.log(getMessageById(4));
console.log(getMessageById(12));

You can view the code on my jsfiddle link here - https://jsfiddle.net/karthikeyan_shanmugavadivelan/3o0udv7f/11/

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 correct way to exclude and remove a portion of the value within an object using TypeScript?

The function useHider was created to conceal specific values from an object with the correct type. For example, using const res = useHider({ id: 1, title: "hi"}, "id"), will result in { title: "hi" } being returned. Attempting ...

Utilizing the Jquery click function to assign an element as a variable

I'm currently working on a script that aims to extract the inner text of any clicked item with the class "customclass". Keep in mind that this specifically targets anchor elements. However, I've encountered an issue where the individual element ...

Encountered an issue with ReactJS app authentication using Firebase and FirebaseUI. Error message reads: "Uncaught Error: Firebase App named '[DEFAULT]-firebaseui-temp' already exists

I'm currently facing an issue in my code. I am working on a single-page web application in ReactJS with 3 tabs. Whenever the user navigates to one tab, the authentication form from FirebaseUI should appear. However, there seems to be a problem as it ...

Using DefaultSeo does not override NextSeo in every component

I am looking to dynamically change the Head tag using next-seo. While browser validation will show NEXTSeo for individual pages, Twitter, Firebase's card validation tool, and others will default to next-seo-config.js. Does anyone have a solution? S ...

The parent-child relationships in MongoDB

In my Meteor application, I have created two collections: ActivityCards and Users. Inside the ActivityCard collection, there is a reference to the User like this: { "_id" : "T9QwsHep3dMSRWNTK", "cardName" : "Guntnauna", "activitycardType" : 1 ...

Convert a JSON object containing strings, integers, and arrays into a map

When working with JSON strings, I prefer to use the Decode() function for unmarshalling: var data Data decoder := json.NewDecoder(input) err = decoder.Decode(&data) The structure of my data is defined as: type Data map[string]interface{} An example ...

Passing Node.js MySQL query results to the next function within an async.waterfall workflow

In my node.js code using express, I have set up a route to request data from a mysql database. My goal is to pass the returned JSON in tabular form to another function to restructure it into a hierarchy type JSON. I have individually tested the script to ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

Showing dummy data in demo mode with an AngularJS table

I stumbled upon this interesting jsfiddle http://jsfiddle.net/EnY74/20/ that seems to be using some demo data. If you check out this example https://jsfiddle.net/vsfsugkg/2/, you'll notice that the table originally has only one row, but I modified it ...

What is the best way to position my content next to my sticky sidebar for optimal visibility?

Just starting out with coding and tackling my initial project using reactJs and bootstrap 5. My aim is to create a sticky side navbar that remains fixed on the side while my content displays next to it, even when navigating through different routes. Unfort ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

Error: Unable to locate module - Invalid generator instance detected. The Asset Modules Plugin has been started with a generator object that does not adhere to the API standards

Encountering an issue in nextjs when utilizing the 'asset/inline' Asset Module Type within a custom webpack configuration while running yarn dev. I attempted to utilize the 'asset/inline' asset module type to output the URI of the impor ...

Tips for incorporating a download button into a video player using Plyr JS

I'm using Plyr JS and I am trying to add a download option for each video. Here is what I've done so far to make the download option work: Even though I have included: controlsList="nodownload" <video controls crossorigin playsinline contro ...

Utilize AJAX to retrieve the output of a PHP randomizer

Current situation: I have a PHP file with a randomizer function and HTML that utilizes this function to display strings from a separate text document. The Function: <?php function rand_line($fileName, $maxLineLength = 4096) { $handle = @fopen($fileN ...

A guide on triggering a function when the context changes in a React application

Can I automatically trigger a function in a component whenever the context changes? Specifically, I have a variable named isLoggedIn in the Navbar module. Whenever a user logs in, the value of isLoggedIn is updated to true. In my Blog module, how can I m ...

What is the process for embedding JQuery within the <body> tags in Joomla 3.1?

I inserted the following code into my default.php file in Joomla 3.1. <?php JHtml::_('jquery.framework'); JFactory::getDocument()->addScript(JURI::root().'template/mytemplate/js/jquery.min.js'); ?> However, this code only pl ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

How can we parse the returned 'data' as HTML in JavaScript/jQuery to select more elements?

After receiving data from a webservice, it turns out that the data is just raw HTML without any XML headers or tags around it, but simply a piece of HTML code. <div class="Workorders"> <div id="woo_9142" class="Workorder"> <span ...

How to locate the data-id of the next element in a jQuery list

Is it possible to retrieve the data-id of the following list element when clicking a button while on the current active list item? <div class="nbrs"> <ul> <li id="item1" data-id="1" class="active ...

Exploring ways to retrieve item metadata from a Stripe checkout session

When setting up a Checkout session, I dynamically create prices using the price_data and product_data properties. I include metadata for each item within the product_data.metadata property. However, after a successful payment is made, I retrieve the sessi ...