Exploring a JavaScript object's array

Greetings, I am looking to develop a simple visual editor for my plugins.

 let x = {
        tag : "a",
        atts : {
            href : "/",
            class : "a",
            text:"link"
        },
        components:[
            {
                tag : "b",
                atts : {
                    class : "a",
                    text:"asdsad"
                },
                components:[
                    //...
                ]
            }
        ]
    }

I have a JavaScript object structured like this. My goal is to extract all the "components" properties from it.

function render_blocks(blocks){
        for (let i = 0; i < blocks.length; i++) {
            const block = blocks[i];
            let $block_html = $("<"+ block.tag +">",{...block.atts});
            if(block.components){
                for (let k = 0; k < block.components.length; k++) {
                    const block_comp = block.components[k];
                    let $block_html_comp = $("<"+ block_comp.tag +">",{...block_comp.atts});
                    $block_html.html($block_html.html()+$block_html_comp[0].outerHTML);
                }
            }
            html = $block_html[0].outerHTML;
            console.log(html);
        }
    }

I am currently using the function above to convert JavaScript blocks into HTML, though I admit it's not the best :P.

Please help me with this...

-Edit: Is there a way to efficiently scan nested components within my object? There could be a large number of them and I'm trying to find an optimal solution.

Answer №1

One way to tackle this problem is by utilizing recursion

let data = {
    tag: "a",
    atts: {
      href: "/",
      class: "a",
      text: "link"
    },
    components: [
        {
            tag: "b",
            atts: {
                class: "a",
                text: "asdsad"
            },
            components: [{ last: "last" }]
        }
    ]
};

let componentsArray = [];

function retrieveComponents(obj) {
    if (!obj.components) {
        return;
    }
    componentsArray.push(obj.components);
    obj.components.forEach(component => retrieveComponents(component));
}

retrieveComponents(data);
console.log("componentsArray ", componentsArray);

Answer №2

I was able to resolve the issue on my own. Solution

// Example code blocks
let x = {
  tag: "a",
  atts: {
    href: "/",
    class: "a"
  },
  components: [{
    tag: "b",
    atts: {
      class: "a",
      text: "asdsad"
    },
    components: [{
      tag: "b",
      atts: {
        class: "a",
        text: "asdsad"
      },
      components: [
        //...
      ]
    }]
  }]
}

function Block(block) {
  this.components = [];
  if (block.components) {
    this.components = block.components;
  }
  this.block = block;
}

Block.prototype.get_components = function() {
  return (this.components ? (this.components.length <= 0 ? false : this.components) : false);
}

Block.prototype.find_inner_components = function() {
  let has_components = this.get_components();
  let parent_components_arr = [];
  let section_components_arr = [];
  while (has_components) {
    let cur_components = has_components;
    has_components = false;
    for (let i = 0; i < cur_components.length; i++) {
      let new_block = new Block(cur_components[i]);
      section_components_arr.push(new_block);
      has_components = has_components || new_block.get_components();
    }
    parent_components_arr.push(section_components_arr);
    section_components_arr = [];
  }
  return parent_components_arr;

}

let a = new Block(x);
console.log(a.find_inner_components())

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

Having difficulty integrating framer-motion with react-router

I've been working on adding animations and smooth transitions to my app using Framer-motion, but I'm facing some challenges in getting it all to function properly. With react-router 6, my goal is to trigger exit animations on route sub-component ...

react-select is not displaying assets correctly within the react-modal component

I am currently utilizing react-select to implement a select field within a modal created with react-modal. However, I am encountering issues with the assets not displaying correctly, as depicted in this image (the arrow is missing and the list is not showi ...

Sharing a new update in the IBM Connections Community

I've encountered an issue where my status update posted to an IBM Connections community is only visible in the Recent Updates section, not in the Status Update section. The URL I'm using is: Here is the JSON I am using: {"object":{"url":"url", ...

What is the best way to set conditions for document side script?

I'm struggling to disable the horizontal scroll when the viewport width is 480px or less. The script that controls the scroll behavior on my website looks like this: <script> $(function () { $("#wrapper").wrapInner("< ...

What is the best way to extract a certain property from a JSON string using JavaScript?

Can you guide me on how to extract the value of agent_code from this string using JavaScript? Additionally, could you please provide an explanation of the underlying logic? Abridged JSON Data: [{"name":"NYC","zone_id":"1","totalagents":"40","agents":[{ ...

When used simultaneously, two jQuery functions fail to operate as expected

Currently in the process of coding my portfolio, I encountered an issue with incorporating two JavaScript/jquery codes together. Firstly, for the first section to be a full-page scroll using fullpage.js "plugin," and secondly, changing the navbar to be tra ...

Using the useNavigation Hooks in React Js, learn the process of sending JSON data efficiently

This is the custom Json file I developed for my application. export const Data = [ { id: 1, title: "Title 1", description: "Description 1 Data", }, { id: 2, title: "Title 2", ...

Tips for live streaming a video file

I am looking to develop a page in asp.net that plays a video file without allowing it to be downloaded on the client side. It should function like a video on YouTube. ...

What is the best way to maintain user authentication using Firebase?

After trying a few solutions I found, I am still struggling to persist user authentication with Firebase after a page refresh. It seems like I might be missing some key concepts. I have been following the Firebase documentation and attempted to implement ...

Trouble accessing data with AJAX

I am trying to retrieve content from a web page and display it on my own webpage using AJAX. However, I keep encountering an "Access denied" error before the specified page is fetched. It's important to note that the target page does not require any l ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Providing access to information even in the absence of JavaScript functionality

Is it possible to make the content of a webpage using jQuery/JavaScript visible even when JavaScript is disabled? Currently, I have a setup where clicking on an h2 header will display information from div tags using the jQuery function. I've made sur ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...

Loop through an object in JQ only if it is present

The structure provided is as follows: { "hits": [ { "_index": "main" }, { "_index": "main", "accordions": [ { "id": "1", "accordionBod ...

Choosing a nested object within a JavaScript object

Is there a way to select the style contents of an object within another object? The data consists of a json encoded array. In my scenario, I am using data[i].replies and getting 2. How can I access data[i].userstyles instead? It seems to be an object. h ...

Acquire JSON data structures using Node.js

I've been struggling to find a solution using just keywords - endless scrolling, yet all I can find are tutorials on getting data from JSON structure, rather than getting data structure from JSON. If you're unsure what my end goal is, here are s ...

Issue with Mjpg paparazzo.js functionality not functioning as expected

I am currently exploring alternative methods to view my security cameras without relying on browser support for mjpg streaming. I have come across Paparazzo.js, which appears to be a promising solution that I want to experiment with: https://github.com/rod ...

How to access the directive object within the controller in AngularJS

Imagine I have a basic directive defined like this: app.directive('someDirective', [function() { return { restrict: 'E', link: function() { }, controller: [function() { // Want to access ...

What is the best way to loop through every element contained within a List of Long values in Java?

I have a method that requires a parameter of List<Long> l. Within the method, there is an if statement that needs to iterate through each value in the List<Long> l. This is the code snippet I am using: public void myFunction(final List&l ...

Is there a way to transform a SQL BIT into JSON using jQuery and then showcase it in an HTML format?

Currently, I am dealing with the interaction of checkboxes and JSON data. My main goal is to find an efficient and clean method to set a checkbox based on JSON data retrieved from a BIT field in SQL. The code snippet below achieves this, but I feel like th ...