Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON keys in order

I have the below in a file and read as

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 am using the below code to loop through the keys

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

});

Inside the each loop, I get the firstname, lastname etc, in the same sequence as in the input file. I want to know if I will get it in order always?

like image 819
Krishnaveni Avatar asked Oct 31 '22 00:10

Krishnaveni


1 Answers

Properties order in objects is not guaranteed in JavaScript; you need to use an Array to preserve it.

Definition of an Object from ECMAScript Third Edition (pdf):

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Since ECMAScript 2015, using the Map object could be an alternative. A Map shares some similarities with an Object and guarantees the keys order:

A Map iterates its elements in insertion order, whereas iteration order is not specified for Objects.

like image 57
vp_arth Avatar answered Nov 11 '22 04:11

vp_arth