0

I have a JSON

    var x = {
    "dialog_trunk_1":{
        "message": "This is just a JSON Test"
    },

    "dialog_trunk_2":{
        "message": "and a test of the second message"
    },

    "dialog_trunk_3":
    {
        "message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
    }
}

Where I need to get all the keys in the order which they are defined. I have seen the Object.Entries ECMA6. Not sure how to use.

I have tried with simple for

keys = []
for(var key in x)
{
keys.push(key)
}

But this order is unexpected.

The expected results must be

keys = ["dialog_trunk_1","dialog_trunk_2","dialog_trunk_3"]
Code Guy
  • 2,205
  • 21
  • 49
  • 4
    Does this answer your question? [Getting JavaScript object key list](https://stackoverflow.com/questions/3068534/getting-javascript-object-key-list) – Adam P. Jan 06 '21 at 11:37
  • [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Đinh Carabus Jan 06 '21 at 11:39
  • In javascript, object properties are not guaranteed a specific order, so if you want to maintain order, you can write the object properties into an array of objects. And then you can loop over that array. – Harshit Mahajan Jan 06 '21 at 11:46
  • "*The expected results must be...*" - why? This feels like you're addressing the wrong problem (see "[what is the xy problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)"); as such if you can tell us the problem you're trying to solve by guaranteeing the order of keys we might be able to offer a more useful solution. – David says reinstate Monica Jan 06 '21 at 11:48

1 Answers1

2

You can use the below

Object.keys(obj)
Jobelle
  • 2,347
  • 1
  • 13
  • 21