Get JSON keys in order

I have the following in a file and read how

var input = require("./mydata.json");

"User": {
        "properties": {
        "firstName": {
          "type": "string",
          "minLength": 1,
          "maxLength": 50
        },
        "lastName": {
          "type": "string",
          "maxLength": 50
        },
        "middleName": {
          "type": "string"
        },
        "title": {
          "type": "string"
        },
        "language": {
          "type": "string",
          "default": "en-US"
        }
      }
    }

I use the code below to scroll keys

var item = _.get(input, 'User');
var properties = item.properties;
var allKeys = _.keys(properties);
_.each(allKeys, function(key) {

});

Inside each loop, I get the first name, last name, etc. in the same sequence as in the input file. I want to know if I can get it in order?

+4
source share
3 answers

The order of object properties is not guaranteed in JavaScript; you need to use Arrayto save it.

Object Definition from ECMAScript Third Edition (pdf) :

4.3.3 Object

. , , . , .

ECMAScript 2015, Map . A Map Object :

, .

+2

. , .

0
Object.keys(input.User).sort();
// Will return all keys in sorted array. 

, , , :

Object.keys(input.User).sort().forEach((key,index)=>{

    console.log('key :'+key+' , value :'+input.User[key]);
})
-1

All Articles