russellmania
russellmania

Reputation: 749

Converting object attributes to array to HTML using .map()

I'm creating an object, putting the attributes of that object into an array and then mapping the array to HTML output and I end up with line after line of commas? Where are these commas coming from?

let results = []

class Polygon {
  constructor() {
    this.name = "Hexagon"
    this.edges = 6
    this.size = 1
  }
  setName(value) {
    this.name = value
  }
  setEdges(value) {
    this.edges = value
  }
  setSize(value) {
    this.size = value
  }
  getArea() {
    return this.size * this.size
  }
}

let shape = new Polygon()
shape.setName("Square")
shape.setEdges(4)
shape.setSize(6)

results.push(shape.name)
results.push(shape.edges)
results.push(shape.size)
results.push(shape.getArea())

console.log(results)

resultsDiv = document.querySelector('#results')
resultsDiv.innerHTML = results.map(r => '<p>' + r + '</p>')

Here's the fiddle with the HTML: https://jsfiddle.net/ruzel/qyrczkup/3/

Upvotes: 1

Views: 851

Answers (2)

Akrion
Akrion

Reputation: 18525

You can also resolve this with reduce and template string since map returns an array and InnerHTML does toString on the array:

resultsDiv.innerHTML = results.reduce((r,c) => r.concat(`<p>${c}</p>`), '')

Upvotes: 1

sjahan
sjahan

Reputation: 5960

map returns another array and when you pass it to innerHTML, it becomes a string version of it.

Just try it: console.log(results.map(r => '<p>' + r + '</p>').toString()) returns: <p>Square</p>,<p>4</p>,<p>6</p>,<p>36</p>

To solve this, just transform that array to a string properly before setting it as HTML:

resultsDiv.innerHTML = results.map(r => '<p>' + r + '</p>').join('')

Upvotes: 5

Related Questions