DEV Community

Discussion on: Converting XML to JSON using Recursion

Collapse
darcher profile image
Dylan Archer • Edited on

For semantic brevity, would you not want to pull the filter func outside the for..of loop? Also utilizing const seems more ideal.

function xml2json(srcDOM) {

  const children = [...srcDOM.children];
  if (!children.length) return srcDOM.innerHTML

  const jsonResult = Object.create(null),
    childIsArray = (x, y) => x.filter(z => z.nodeName === y.nodeName).length > 1;

  for (const child of children) {
    if (!childIsArray(children, child)) jsonResult[child.nodeName] = xml2json(child);
    else {
      if (jsonResult[child.nodeName] !== undefined) jsonResult[child.nodeName].push(xml2json(child));
      else jsonResult[child.nodeName] = [xml2json(child)];
    }
  }

  return jsonResult;
}
Enter fullscreen mode Exit fullscreen mode

I am researching how others approached this scenario due to a similar surprise on my current project. Nice approach!