What is the best way to retrieve an ID when parsing JSON recursively?

Could you provide guidance on how to retrieve the IDs of all children when parsing JSON data?

I have attempted to use a recursive function, but it seems to be calling infinitely.

For reference, here is my code snippet: http://jsfiddle.net/Ds8vQ/

for(var i=0;i<json.children.length;i++){
    console.log(json.children[i].id);
    recusionGet(json.children[i]);
}
function recusionGet(obj){
    console.log(obj)
    if(typeof(obj.children)!="undefined"){
        // alert('--')
        for(var i=0;i<obj.children.length;i++){
            console.log(json.children[i].id);
            recusionGet(json.children[i]);
        }
    }
}

b
  b-a-1
  b-b-2
     b-b-a
     b-b-b

Answer №1

  1. Remember to parse objects, not JSON strings.
  2. For further assistance, check out this Answer

Sample code snippet

var idLine = "";
recursionGet(json);
function recursionGet(object){
    for (var elem in object ){
        if(typeof(object[elem]) == "object"){
            recursionGet(object[elem]);
        }
        if(elem == "id"){
            idLine += object[elem] + "|";
        }
    }     
}
console.log(idLine);

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

``The Art of Handling REST API with Express and Mongoose

Running Express on my application, I have a delete route set up as shown below: router.route('/lists/:id') .delete(function(req, res){ Entry.remove({ _id: req.params.id }, function(err, list){ if(err) ...

What is causing the issue with Vue.js :class not functioning properly when it relies on a property of a list

Here is a snippet of my HTML code: <tr v-for="product in products" :class="{'bg-red': product.toWrite }" :key="product.name"> <td @click="setObjectToWrite(product.name)" class="show-hover&qu ...

Retrieve only the initial tag content using jquery

My goal is to extract the "22" from the following code... <div class="left"> <a class="count-link" href="http://url1.com"> <span>22</span> users </a> <a class="count-link" href="http://url2.com"> <span>10</span ...

Revamp the jQuery dynamic form script to be adaptable for various uses

My form is designed with simplicity in mind, allowing users to choose a color and then an item from that color category. The second selection updates based on the first input. Currently, I have a jQuery script that targets the first element by ID and chan ...

What steps are involved in adding an image to an autocomplete script?

I need help adding an image to my autocomplete script. Below is my code that I'm struggling with. My Controller: function getsearch($c_id) { $searchTerm = $_GET['term']; $query = $this->db->query("SELECT state_name FROM state ...

What is the most efficient way to organize JSON data in a tree structure using JavaScript?

I have a JSON data structure that I need to transform into a different format. The original JSON format: values = an array containing objects that need to be filtered by action === 'commented' comment = an object with the comment, n Tasks, and ...

In what way can I obtain CSS comments utilizing jQuery?

I am trying to figure out how I can access CSS comments that are included in an external stylesheet. In order to demonstrate, I have loaded a sample CSS using the following code: <link rel="stylesheet" type="text/css" media="all" href="test.css" /> ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

remove item from list of objects

Currently, I am actively using vuejs 3 in conjunction with laravel. This is the object array that I am currently working with: [[Target]] : Array(3) 0: Proxy(Object) {id: '96', name: 'DESINCRUSTADOR DCALUXE - HIDROCAL ELECTRONICO', cat ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...

Cannot get object state to update using React hook

I'm not very experienced with React. I attempted to set the state as an object by fetching data from an API. The fetching process returns the correct object, but for some reason setting the state is not functioning correctly. const [info, setInfo] = ...

Preventing CSRF attacks using AJAX in a Django application

After some troubleshooting, I discovered the mistake in my HTML code. Simply adding {% csrf_token %} resolved the issue :) Big thanks to everyone who helped! (I followed the JavaScript snippet provided in the initial response but I'm still encounte ...

Can I securely hand off a JavaScript callback to an FFI function that executes it in a separate thread?

I need to use a C function that takes a callback and executes it on a separate thread: void execute_in_new_thread(void (*callback)()) { // create a new thread and run `callback` in it ... } To accomplish this from JavaScript using Node-FFI, I have to ...

The jQuery upload feature fails to function properly when attempting to upload multiple images simultaneously on a single webpage

Overview: I am currently in the process of developing an instant upload feature using Jquery/Ajax. The goal is to display a Fancybox with an upload field when a user double-clicks on an image. Once the user selects an image, it should be uploaded and the s ...

Error: ajax is not defined and needs to be declared (repeated twice)

Currently, I have a form that requires processing using Ajax. <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <div class="column1"> <form class="form box" action="javascript:networkCheck();" ...

Performing calculations with jQuery to extract the value of a selected dropdown option and a text

I am attempting to calculate the total amount by multiplying the value entered in a text box labeled qty1 by the price retrieved from a select box using ajax. <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

What is the best way to pass my request data to my $scope variable?

I'm currently facing a challenge with this particular topic. My goal is to add the response data that I retrieve from Express to my angular $scope and then direct the user to their profile page. This is how my Controller Function is structured: $sc ...

Tips for aligning an image in the middle of a column within an ExtJS GridPanel

My goal is to center the icon horizontally within the "Data" column: Currently, I have applied textAlign: center to the column: Additionally, I am using CSS in the icon renderer function to horizontally center it: Despite these efforts, the icon remains ...

Having trouble obtaining information from the state with Pinia Store

Currently, I am delving into the world of the composition API and Pinia with Vue3. I am facing an issue while calling an external API to fetch data and store it in the state of my store. The problem arises when I try to access this state from my page - it ...