I have an array with content similar to this:
const array = [["name", "age", "city", "email"],["Peter", "30", "Madrid", "[email protected]"],["Josh", "23", "NY", "[email protected]"] ]
And I have to return the content in this format:
<data>
<name>Peter</name>
<age>30</age>
<city>Madrid</city>
<email>[email protected]</email>
<name>Josh</name>
<age>23</age>
<city>NY</city>
<email>[email protected]</email>
</data>
I've tried every idea that has come to mind with no luck, so any help is welcome.
CodePudding user response:
Using for
loops, one to iterate arrays, another to iterate values.
const array = [
["name", "age", "city", "email"],
["Peter", "30", "Madrid", "[email protected]"],
["Josh", "23", "NY", "[email protected]"]
]
const labels = array.shift()
let output = '<data>'
for (const item of array) {
for (let i = 0; i < 4; i ) {
output = `<${labels[i]}>${item[i]}</${labels[i]}>`
}
}
output = '</data>'
document.getElementById('txt').value = output
textarea {
width: 100%;
height: 100px;
}
<textarea id="txt"></textarea>