1

Using JavaScript, I am trying to create the following object:

{name: "John Doe", grade: "3", 6: "six"}

Note that the key for the third element is a number, 6.

I am creating the object as follows:

var myObject = {};

// Some code goes here

myObject["name"] = "John Doe";

// Some more code goes here

myObject["grade"] = "3";

// And even more code here

myObject["6"] = "six";

Now, the problem is the object gets constructed as follows

{6: "six", name: "John Doe", grade: "3"}

Note that the element 6: "six" moved to the front of the object even though it was added last.

I noticed that all elements that have numbers as their keys get added to the front even though they get added after other elements. How I ensure that the elements are not re-arranged and keep my original order?

Thanks.

Greeso
  • 5,502
  • 6
  • 43
  • 65

1 Answers1

0

My simple answer is not possible.And this not a problem.Because object does not have sorting function.It's a default behaviour of the object.And also you calling the object values via key name, not the index.so sorting was not necessary

var a ={6: "six", name: "John Doe", grade: "3"};

console.log(a['6']) // calling by keyname so position not a problem with that

Updated

If you need an order .use with array

var myObject = [];

myObject.push({name : "John Doe"});
myObject.push({grade : "one"});
myObject.push({6 : "six"});

console.log(myObject)
prasanth
  • 19,775
  • 3
  • 25
  • 48