5

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?

Marcus Höglund
  • 13,944
  • 9
  • 42
  • 63
Krishnaveni
  • 789
  • 2
  • 10
  • 30
  • 2
    I believe, you can't rely on that order. Hash table must not to preserve it. It's just lucky implementation. – vp_arth Jul 06 '16 at 05:42
  • Property order is a [complex subject](http://stackoverflow.com/a/38218582/6445533) in Javascript –  Jul 06 '16 at 07:49

3 Answers3

2

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.

vp_arth
  • 12,796
  • 4
  • 33
  • 59
0

Yes, If you want to change the order then you will need to sort or arrange the keys in a separate array and then loop on rearranged array.

Mahesh
  • 772
  • 5
  • 18
0
Object.keys(input.User).sort();
// Will return all keys in sorted array. 

Then , if you want to read value of each key following that order , just loop through that array :

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

    console.log('key :'+key+' , value :'+input.User[key]);
})
Abdennour TOUMI
  • 64,884
  • 28
  • 201
  • 207
  • 3
    I think the OP means the order they were defined, not some arbitrary order for the sake of it. – Marty Jul 06 '16 at 05:55