Access composite word object, $ .each, Javascript?

2

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

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

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

I use each to iterate:

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

How to access Public Health ?

    
asked by anonymous 11.09.2017 / 22:13

1 answer

6

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

But the problem here is another one. You can not use $.each alone, you must use Object.keys .

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

So corrected will be:

    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>

OrinnativejavaScript:

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);
});
    
11.09.2017 / 22:17