Map html element to json object

Viewed 114

I have an html element like this,

<div class='myparent'>
    <div>
        <div class="pdp-product-price">
            <span> 650 rupees</span>
            <div class="origin-block">
               <span> 1,500 rupees</span>
               <span>-57%</span>
            </div>
        </div>
    </div>
</div>

I need to create a json of this 'myparent' div.

{
    "div": {
        "div": {
            "div": {
                "span": {},
                "div": {
                    "span": {},
                    "span": {}
                }
            }
        }
     }
}   

Is there a way to do this in javascript?

2 Answers

You can use children property of HTMLElement

Then iterate over parent recursively and get subtree.

But be aware that you cannot assign two values with the same key. Therefore, you can use an index when assigning subtree like

  "div": {
     "span_1": {},
     "span_2": {},
  }

Hope the below snippet will give you a clue.

const parent = document.getElementById('parent')

const tree = {};


const getTree = (elem) => {
   const subtree = {};
   for(let child of elem.children){
       subtree[child.tagName.toLowerCase()] = getTree(child)
   }
   return subtree;
}

tree[parent.tagName.toLowerCase()] = getTree(parent);

console.log(tree);
<div id="parent" class='myparent'>
  <div>
    <div class="pdp-product-price">
      <span> 650 rupees</span>
      <div class="origin-block">
        <span> 1,500 rupees</span>
        <span>-57%</span>
      </div>
    </div>
  </div>
</div>

Recursive function that builds the json. To ensure no issues with the keys (that have a possibility to be duplicates) the following was added :n where n is the index of the element.

function htmlToObject(targetElement) {
  return Array
    .from(targetElement.children)
    .reduce((acc, cur, i) => {
      acc[`${cur.tagName}:${i}`.toLowerCase()] = htmlToObject(cur);
      return acc;
    }, {});
}

const startElement = document.getElementsByClassName("myparent")[0];

const res = {
  [startElement.tagName.toLowerCase()]: htmlToObject(startElement)
};

console.log(res);
<div class='myparent'>
  <div>
    <div class="pdp-product-price">
      <span> 650 rupees</span>
      <div class="origin-block">
        <span> 1,500 rupees</span>
        <span>-57%</span>
      </div>
    </div>
  </div>
</div>

Related