Access compound word object, $.each, Javascript?

Asked

Viewed 55 times

2

I have a problem accessing an object that has white space in its name.

I used json Encode in php and get the answer so from ajax:

{Seguranca: 0, Saude Publica: 4, Transportes: 0, Outros: 0, Urbanizacao: 0, …}

use each to iterate:

$.each(pontos, function(index, ponto) {}

as access the Saude Publica ?

1 answer

6


To access properties with spaces you can use ['nome da propriedade'].

But the problem here is another. You can’t use the $.each alone, you have to use Object.keys.

In fact the $.each accepts and iterates objects. But in this case the callback API is (nomeDaPropriedade, valor)

Thus it will be corrected:

    var objeto = {
      'Seguranca': 0,
      'Saude Publica': 4,
      'Transportes': 0,
      'Outros': 0,
      'Urbanizacao': 0
    };

    $.each(objeto, (chave, valor) => {
      console.log(chave, valor);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or in native Java:

var objeto = {
  'Seguranca': 0,
  'Saude Publica': 4,
  'Transportes': 0,
  'Outros': 0,
  'Urbanizacao': 0
};

Object.keys(objeto).forEach((chave) => {
  const valor = objeto[chave];
  console.log(chave, valor);
});

  • warrior worth!

  • @Abnerpassosmagalhaes actually had an error in the answer... corrected.

Browser other questions tagged

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