Augustus Brennan
Augustus Brennan

Reputation: 147

Putting Key-Value Pairs in an Object - Why does it Order the entries by #?

Below is my code. I'm putting a number and it's double as key-value pairs into an object. I'm curious as to why it is ordering the result by #. As in why does the '13': 26 entry come before '21': 42, when 13 comes after 21 in the array? Thanks for any insight.

var array = [1,2,3,4,5,8,7,21,13];
var object = {};

for (var i = 0; i < array.length; i++){
object[array[i]] = double(array[i]);
}

function double(a){
return a*2;
}

console.log(object);

Here is what I get in my console:

{ '1': 2,
'2': 4,
'3': 6,
'4': 8,
'5': 10,
'7': 14,
'8': 16,
'13': 26,
'21': 42 }

Upvotes: 3

Views: 75

Answers (1)

Divyanshu Maithani
Divyanshu Maithani

Reputation: 14996

JavaScript objects are generally not ordered and you shouldn't rely on the properties to be in order. You can try this snippet to get the result in order:

var array = [1,2,3,4,5,8,7,21,13];
var object = {};

for (var i = 0; i < array.length; i++){
object[array[i]] = double(array[i]);
}

function double(a){
return a*2;
}

console.log(JSON.stringify(object));


EDIT

The above snippet will not guarantee the order because:

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.

So the order you're getting in your code will depend on how your browser interprets it (since there is no exact rule defined it might sort by keys in ascending order).

A method to preserve this order is to use arrays (which are ordered). This is an example using array of objects:

var array = [1,2,3,4,5,8,7,21,13];
var object = []; // changed this to an array

for (var i = 0; i < array.length; i++) {
  var newObject = {};
  
  // in order to insert keys as variables
  newObject[array[i]] = double(array[i]);
  object.push(newObject);
}

function double(a){
return a*2;
}

console.log(object);

Note: I've created an object first before pushing it to the array. This is necessary if you want your key values to be set from some variable.

Upvotes: 1

Related Questions