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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With