0

I'm building JSON with JavaScript. Here's my object:

catalogoJSON = {
    condicion: condicionCatalogos0,
    tipo: tipoCatalogos0,
    idCatalogo: idCatalogo0,
    valor: valorCatalogos0
};

But when I print it with Firebug, I get my properties printed alphabetically like this:

{
    condicion: condicionCatalogos0,
    idCatalogo: idCatalogo0,
    tipo: tipoCatalogos0,
    valor: valorCatalogos0
}

Is there a way in JavaScript to get back my JSON with its properties in the order that I declare them, without having to change my properties' names?

Ry-
  • 218,210
  • 55
  • 464
  • 476
linker85
  • 1,601
  • 5
  • 26
  • 44
  • 1
    Why would you want them in order? Object properties' order is not guaranteed anyways therefore it should not matter. – Joseph Jul 24 '12 at 17:48
  • possible duplicate of [Does JavaScript Guarantee Object Property Order?](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – epascarello Jul 24 '12 at 17:51
  • for the application i´m developing it´s important that i get them in the order i declare them. – linker85 Jul 24 '12 at 17:52
  • 2
    @linker85: Then use an array instead. – gen_Eric Jul 24 '12 at 17:53

1 Answers1

4

Objects in JavaScript have no inherit order. Firebug just prints then alphabetically, because it feels like it (Chrome's dev tools to that too).

You can try to loop through the object, and print it yourself, that may keep the order.

for(var x in catalogoJSON){
    console.log(x, catalogoJSON[x]);
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • well put my json in the order that i wanted + the example from above managed to do the trick. – linker85 Jul 24 '12 at 17:53
  • 1
    As far as I know, browsers do keep them in order during a loop but standards suggest that they shouldn't be. So... I'd not rely on it. – Joseph Jul 24 '12 at 17:53
  • @linker85: If this worked for you, you should [accept the answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235). (I only mention it because I noticed you haven't accepted any answers anywhere else. You should do the same for those if any of the answers answered your question.) – Ry- Jul 24 '12 at 18:06
  • 1
    mmh so that´s where you click acept answers. – linker85 Jul 24 '12 at 18:09