What is the best way to retrieve a specific children element from a JSON object in JavaScript based on a keyname and value match

Recently, I encountered a JSON data structure that looked like this:

var jsonData = {
    "id": 0,
    "content": "abc",
    "children" : [{
        "id": 1,
        "content": "efg",
        "children" : []
        }
        {
        "id": 2,
        "content": "hij",
        "children" : []
        }
    ]}

I am interested in extracting the children part of the JSON by searching for a specific key and value combination. For example:

 if(id == 2)

If the condition holds true, then I can access jsonData.children[1] and perform operations on it. This approach reminds me of using Hashtables in Java and C#. Unfortunately, JavaScript does not have built-in hashtable support.

Therefore, I am seeking any possible solutions to efficiently tackle this problem.

Answer №1

To find an object in a collection using recursion and a reducer, you can implement the following function:

function findObjectById(idToFind, collection) {
  return collection.reduce(function(accumulator, currentObj) {
    if (currentObj.id === idToFind) {
      return currentObj;
    } else if (currentObj.children.length > 0) {
      return findObjectById(idToFind, currentObj.children);
    } else {
      return accumulator;
    }
  }, null);
}

findObjectById(2, [jsonData])
//^ {id: 2, content: 'hij', children: []}

If the function does not find any object with the specified id, it will return null.

Answer №2

If you want to filter the data, try using the filter method:

var targetId = 5;
var results = jsonData.children.filter(function (item) {
    return item.id === targetId;
});

UPDATE: Introducing a recursive solution

In addition to the concise and efficient solution provided by @elclanrs in the previous answer (which is highly recommended), here is an alternative approach for handling recursion.

var matches = [];
function searchForMatches(children, targetId) {
    if (children && Array.isArray(children)) {
        var newResults = children.filter(function (item) {
            return item.id === targetId;
        });
        Array.prototype.push.apply(matches, newResults);
        for (var i = 0; i < children.length; i++)
            searchForMatches(children[i].children, targetId);
    }
}
searchForMatches(jsonData.children, 7);
console.log('All matching items:', matches);

Run it on JS Fiddle: http://jsfiddle.net/q1owtj3h/

Answer №3

Did you know that in Javascript, objects are essentially Maps? Take a look at this example:

var person = {}
person[1] = {"id": 1, "name": "Alice"}
person[2] = { "id": 2,"name": "Bob"}

You can easily access the value like this:

var name = person[1].name;

I hope this explanation clarifies things for you!

Answer №4

Here's a method that I discovered. It was influenced by @Jason W , @Mr.Green and @elclanrs .

I decided to give it a try, and surprisingly, it worked.

However, there are still some aspects that puzzle me about why this method is effective, and I will be posting my queries shortly. Feel free to take a look if you can offer assistance.

var dataMap = {};

function matchData (jsonObj) {
  dataMap[jsonObj.id] = jsonObj;

  if (jsonObj.children.length > 0) {
    for (var i = 0; i < jsonObj.children.length; i++) {
      dataMap[jsonObj.children[i].id] = jsonObj.children[i];

      if (jsonObj.children[i].children > 0) {
        matchData(jsonObj.children[i]);
      }
    }
  }
}

matchData(jsonData);
console.log(dataMap[2]); 
//you will get "{"id": 2,"content": "hij","children" :[]}

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

Developing a custom function within an iterative loop

Can someone assist me with a coding problem? I have these 4 functions that I want to convert into a loop: function Incr1(){ document.forms[0].NavigationButton.value='Next'; document.PledgeForm.FUDF9.value='Y1'; document.fo ...

Angular select automatically saves the selected option when navigating between views

I would like the selected option in my dropdown menu to stay selected as I navigate through different views and then return back. Here is the view: <select ng-model="selectedSeason" class="form-control" ng-options="season as 'Season '+ seas ...

JavaScript for creating dropdown menus using Twitter Bootstrap

I've been struggling to get the dropdown menus in my Twitter Bootstrap project to function properly. Below is the code I have for the navbar: <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> < ...

Moving a DOM element within AngularJS to a new location

I have created an angular directive that functions like a carousel. To keep the dom element count low, I delete elements from the dom and then re-insert them using angular.element to select, remove, and insert items as shown below: app.directive('myD ...

Obscure unidentified attribute within JSON error object

In my node.js console script, I am utilizing pg-promise. Node version: v0.10.38 pg-promise version: 1.1.4 A connection error occurred due to a simple misconfiguration issue that was not very informative. I would like my script to provide a detailed expla ...

Creating a Chart.js line plot with discontinuous sections (jumps)

Using Chart.js, I have created a line chart and am looking to avoid rescaling the x-axis for more sample points. What is the most effective method to showcase jumps when y axis values change abruptly? Ideally, I want to be able to assign two y values per ...

Incorrect scope value detected in Angular controller

I recently started learning Angular 1, and I've encountered an issue with my code: var app = angular.module("Football", []); app.factory("competitions", ['$http', function($http) { return $http.get("json/competitions.json") .success(fu ...

Error: A SyntaxError was encountered due to a missing closing parenthesis after an argument list while writing JavaScript within PHP code

I'm facing an issue writing JavaScript within PHP code. Here's my script : echo ' <script>'; echo ' $(function(){'; echo ' x = parseInt($("#counter2").val());'; echo ' $("#add_row2").click(function(){&apo ...

Extract the href value from an element and append it to the src attribute of an image

How can I extract the href link from the .image1 div class? <div class="image1"> <a href="/images/productA.jpg"> </a> </div> Then, how do I insert it into the image src shown below? <ul class="example"> <li class ...

The express.js GET method is unable to retrieve the value of req.body

I have experience working with Vue3, Vuex, Express.js, and MySQL. In the code snippet below, when I use the router get method, I noticed that calling "console.log(req.body)" displays "[object Object]", and calling "console.log(req.body.userid)" shows "unde ...

Prevent selection on all elements except for input fields with the type of text

I am facing a challenge where I need to prevent selection on a website page for everything except input[type=text] elements. The answer provided in this accepted response to a similar query almost solves the issue. However, it doesn't stop users from ...

Issues with the script manager functionality in asp.net

I need to display a message to the user after submitting a form and include the ID received from the database in the message like this: int reqid = getIDFromDatabase(); string scrp = "<script>alert('Your request has been submitted successfully ...

How to retrieve textfield value using Material UI and ReactJS

Just delved into the world of React and I'm struggling to figure out how to retrieve the value inputted in my textfield when the submit button is clicked. I've been referencing the examples provided here: but unfortunately, they don't addre ...

The functionality of AngularJS's state URL depends on numerical URLs for navigation

Currently, I am utilizing the following URL in my state setup: .state('forum.spesific', { url: '/:articleId', templateUrl: 'modules/forum/client/views/forum.client.view.html', controller: 'forumCont ...

What is the process for executing mocha tests within a web browser?

Am I the only one who thinks that their documentation lacks proper instructions on running tests in the browser? Do I really need to create the HTML file they mention in the example? How can I ensure that it runs the specific test cases for my project? I ...

ReactJS is encountering a situation where two children are using the same key and causing

When I try to view the profile information of another user, I encounter a duplicate key error that says: "Warning: Encountered two children with the same key, ``. Keys should be unique so that components maintain their identity across updates. Non-unique k ...

Storing form data in a file using React

I am trying to create a feature in my react component where instead of submitting a form and sending the data, I want to write this data to a file for later use. Is it achievable using vanilla JS or should I consider using a library? This is how my handl ...

Misunderstandings between HTML and CSS

Can someone please clarify how the functionality of the active-slide class? Code: <div class="slider"> <div class="slide active-slide">..</div> <div class = "slide slide-feature">..</div> <div class = "slide">..</di ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...

Utilizing a series of linked jQuery functions

Is there a more efficient way to write this code snippet? $('#element').html( $('#element').data('test') ); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="el ...