loading...

Discussion on: Converting XML to JSON using Recursion

Collapse
darcher profile image
Dylan Archer

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;
}

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