Uncover and control nested objects in JSON data

Having a dynamic foo object with the possibility of nested parent objects raises the question of how to effectively:

1) Determine the last object that has a parent?

2) Create an array containing all nested parent objects along with the initial obj (foo.obj)?

 foo: {
    caption: "Italian",
    code: "",
    id: 17,
    parent: {
       caption: "Restaurants",
       code: "",
       id: 9,
       parent: {
          caption: "Food and Drink",
          code: "food_and_drink",
          id: 1,
          parent: ""
      }
   }
};

Would implementing a while loop be appropriate for this task?

Answer №1

If you decide to go with vanilla JS only.

1a. Going the loop route:

function findLastParentElement(el) {
    var parentElement = el,
        notFound = true;
    while (notFound) {
        if (parentElement.parent) {
            parentElement = parentElement.parent
        } else {
            notFound = false;
        }
    }
    return parentElement;
}

1b. Opting for recursion instead (remember to watch out for call stack size, as a new function pointer is created each time):

function findLastParentElement(el) {
    if (el.parent) {
        return findLastParentElement(el.parent)
    } else {
        return el
    }
}

2a. Embracing recursion again (using a loop will lead to a code similar to point 1):

function getAllElementsAsArray(el, acc) {
    acc.push(el);
    if (el.parent) {
        return getAllElementsAsArray(el.parent, acc);
    } else {
        return acc;
    }
}
var result = getAllElementsAsArray(root,[]);

Answer №2

If you seek recursivity, look no further. Follow these steps:

#1 Develop a function that checks if an object contains any data in its parent property.

#2 If there is data within your object's parent, proceed to iterate through it. Iterate(OBJ.parent)

#3 When the object is devoid of any data, consider it as the final element (return OBJ).

Once you tackle this issue, challenge yourself by attempting to resolve it with multiple parents/nodes and display all elements in the last nodes.

foo: {
        caption: "Italian",
        code: "",
        id: 17,
        parent: {
           caption: "Restaurants",
           code: "",
           id: 9,
           parent:[ {
              caption: "Chairs and Tables",
              code: "chairs_and_tables",
              id: 2,
              parent: ""
           },
           {
              caption: "Food and Drink",
              code: "food_and_drink",
              id: 1,
              parent: ""
          }]
       }
}

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

Is there a way to activate an event when using # or @ in a text field on React/Next.js?

I'm in the process of starting a new project and I am thinking about how to incorporate this into react/nextjs. I want to create a user selection or hashtag selection dialog around the textarea, but I haven't been able to find any helpful article ...

Why isn't the login redirect script working without any errors or redirection?

Struggling to develop a Greasemonkey script that can automatically fill in certain forms and then redirect to another URL once the form is submitted. // ==UserScript== // @name usersaime // @description fills data form for user and pass // @include h ...

Developing a jsp page with interconnected drop down menus

I am looking to dynamically populate the options in a second drop-down based on the selection made in the first drop-down. For instance, if I have a first drop-down with options {India, South Africa, USA}, and I choose India, then the second drop-down shou ...

Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file a ...

Issue with JavaScript code for Google Maps API not functioning as expected

Can someone help me troubleshoot why my simple Google Maps setup isn't working? Thanks! HTML <script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBy2rXc1YewdnqhPaaEd7H0I4DTV_pc7fo&"> </script> <div id="map"> & ...

How can I design unique navigation menus using HTML, CSS, JavaScript, and jQuery?

Is there a way to create menus where clicking on a holiday/seasonal category opens up all related lists automatically? For example: https://i.sstatic.net/Nctd1.png I've been searching online for submenu options but haven't found the right metho ...

Marionette - Apply a class to the parent ItemView's tagname

I've been working with Bootstrap accordion panels and I'm trying to assign a class to the parent panel of the panel-collapse. Essentially, what I want to achieve is: if (child element) hasClass('panel-collapse.in') { this.addClass ...

three.js fur effect not appearing on screen

I have been working on understanding and implementing fur in three.js. I came across an example at which I used as a reference to comprehend the code. The model loads successfully, but the issue arises when the fur texture doesn't load. I have check ...

ASP.NET can have issues with the functionality of jQuery AJAX

I'm currently working on an asp.net webform project and I'm looking to implement jQuery ajax functionality. Below is the code snippet I have so far: <asp:Button ID="btn_comment" runat="server" CssClass="contact_btn pull-right" Text="send" OnC ...

Is there a way to make an accordion close from a nested component in react?

I'm in the process of developing a page to update product information on an e-commerce platform using NextJS. On the individual item page, I have structured the image upload section within an accordion. After the images are uploaded, I want to reset t ...

Evaluate One Input Value to Determine Another Input Value

Hey there, I've made an update to the fiddle but let me clarify what I'm trying to achieve. My goal is not to implement form validation as I already have that covered with the HTML5 "required" attribute. What I'm aiming for is to customize t ...

What are the steps to start using the Intersection Observer API right away?

Utilizing the Intersection Observer API, I can accurately determine whether an element is within the viewport or not. Is there a way to utilize the Intersection Observer API to detect if an element is in the viewport without relying on a callback function ...

Error: The 'price' property is undefined and cannot be read at path C:NODEJS-COMPLETE-GUIDEcontrollersshop.js on line 45, character 37

I have been attempting to add my products to the cart and calculate the totalPrice, but I keep encountering an error. Here is the error message:- enter image description here. Below is the code from my shop.js file:- exports.postCart = (req, res, next) =&g ...

Trouble with rendering inline images from markdown files in GatsbyJS

I've been trying to include inline images in my markdown file with the gatsby-remark-images plugin. However, I'm facing an issue where the image is not loading on my local host. I'm not sure if it's a syntax error or if I'm missing ...

Ensuring scope safety in jQuery AJAX requests

My intuition suggests that if I am on a laggy server and the user triggers two events quickly enough, the value of c in the success function will be based on the most recent event, potentially causing func1 to use the incorrect value. This is merely a hypo ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

What is the optimal method for generating numerous records across various tables using a single API request in a sequelize-node.js-postgres environment?

I need to efficiently store data across multiple separate tables in Postgres within a single API call. While I can make individual calls for each table, I am seeking advice on the best way to handle this. Any tips or suggestions would be greatly appreciate ...

How can I attach a cookie to a div that becomes visible after a few seconds of video playback?

After 20 seconds of video play, a div element appears. I am trying to set up a cookie so that once the div is shown, it continues to appear unless the user clears their cache (cookie logic). This is my current attempt - http://jsfiddle.net/9L29o365/ Any ...

Exploring the world of JSON communication through MVC Web API: A comprehensive guide

Similar cases to mine have been answered before, but my specific needs always seem to differ from others' problems. I am facing an issue where I'm sending JSON data from my HTML page to the MVC Web API, but unfortunately, the data I receive is a ...

What is the purpose of using square brackets in the angular.module() function in AngularJS?

const myapp=angular.module('myApp',[]); As someone venturing into the realm of angularjs, I have a question. What is the significance of using [] in angular.module()? If anyone could shed some light on this, it would be greatly appreciated. ...