Concatenate string into javascript object

Asked

Viewed 168 times

0

Could someone help me understand why I can’t locate the region on the object.

<img src="mapa.jpg" usemap="#image-map" class="img__map">

const map = document.querySelector('.mapa');

const contentMap = {
    sudeste : {
        title : 'Sudeste',
        conteudo : "Lorem ipsum"
    },
    norte : {
        title : 'Norte',
        conteudo : 'Lorem'
    }
}

map.addEventListener('click', function(e){
    e.preventDefault();

    const region = e.target;

    //pego o valor do alt do mapa
    let regiaoNome = region.alt


    //adiciono o valor do mapa com base no nome do alt clicado
    console.log(contentMap.regiaoNome.title)

})
  • 3

    It’s confusing the question. You use document.querySelector('.mapa') but the class of example is img__map; You want to take the property alt but HTML doesn’t even have that attribute. Nothing is making sense. You could edit your question and explain better what you want?

  • 1

    If I understand correctly you want to access the title property through the key, try: contentMap[regiaoNome].title

  • pq there is no contentMap.regiaoName, just contentMap.sudeste and contentMap.norte. What I knowto understand in your question

1 answer

0

there in the console.log() put so to access the property of the object:

console.log(contentMap[regiaoNome].title)

done this, it will access the region in the contentMap object.

for example:

<script>
document.addEventListener('DOMContentLoaded', () => {
  const map = document.querySelector('.mapa');

  const contentMap = {
    sudeste: {
      title: 'Sudeste. Agora nao vai retornar undefined',
      conteudo: "Lorem ipsum"
    },
    norte: {
      title: 'Norte',
      conteudo: 'Lorem'
    }
  }

  map.addEventListener('click', function (e) {
    e.preventDefault();

    const region = e.target;

    //pego o valor do alt do mapa
    let regiaoNome = region.alt;


    //adiciono o valor do mapa com base no nome do alt clicado
    console.log(contentMap[regiaoNome].title)

  })
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.