| 125 | |
| 126 | // Function to change each node |
| 127 | function traverse(node) { |
| 128 | // Store the new node |
| 129 | const newNode = {}; |
| 130 | |
| 131 | // Repeat with all children nodes |
| 132 | for (const child of node.children) { |
| 133 | // traverse the child |
| 134 | let newChild = traverse(child); |
| 135 | |
| 136 | // If there are no children of the child than it should become a text value |
| 137 | if (child.children.length === 0) { |
| 138 | newChild = child.innerText; |
| 139 | } |
| 140 | |
| 141 | // If the new node already has a key of the child's name it will become an array |
| 142 | if (newNode[child.name]) { |
| 143 | // If it is an array, push the new child |
| 144 | if (Array.isArray(newNode[child.name])) { |
| 145 | newNode[child.name].push(newChild); |
| 146 | } else { |
| 147 | // If it is not an array, change it into one |
| 148 | newNode[child.name] = [newNode[child.name], newChild]; |
| 149 | } |
| 150 | } else { |
| 151 | // If it is not in the keys, set the child as a value in the new node |
| 152 | newNode[child.name] = newChild; |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // Return the new node |
| 157 | return newNode; |
| 158 | } |
| 159 | } |