2

I have a JSON in which keys are in following order:

var JSON= {"code" :1, "country": "US", "node": 1, "region": "abc, "time": 34};

Now this JSON is passed to a Handlebars template which parses it and puts these values in a table in the same order as the keys.

I want to shuffle the order of the keys so that instead of the order that is there in JSON, the keys can get accessed in this order:

node, time, region, code, country

Is there anyway in Javascript that we can alter the order of the keys?

Nikhil Tikoo
  • 325
  • 8
  • 26
  • no Javascript objects properties are unordered by definition; so sorting them is meaningless. – Mahi Dec 06 '16 at 10:00
  • You made the statement, "the keys can get accessed in this order." You can access keys in that order in a function. Or, if you want a JSON string in that order you could build it manually with a function as well. – Tim Dec 06 '16 at 10:05

1 Answers1

0

Object keys don't assure a specific order,

but if you know the keys you can map it directly:

var o = {
    "code": 1,
    "country": "US",
    "node": 1,
    "region": "abc",
    "time": 34
};

var order = ['node', 'time', 'region', 'code', 'country']

var res = order.map( x => o[x] )

console.log(res)
Community
  • 1
  • 1
maioman
  • 15,071
  • 4
  • 30
  • 42