Scanning an array js object

Tags: , ,



Hello, I want to make a basic 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 an js object like this. I want to get all “components” properties in this.

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 using a this function to convert js blocks to html. However this func is very bad :P.

Please HELLLP…

-Edit: How can I scan nested components properties in my object? They may be a lot of. I am searching a efficient way.

Answer

You can use recursion

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

  let componentsArray = [];

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

  getComponents(x);
  console.log("componentsArray ", componentsArray);


Source: stackoverflow