Arch
Arch

Reputation: 625

Angular default sorting in object

I created some object and put key, value into him.

var obj = {};

obj.Z = "val1";
obj.Y = "val2";
obj.X = "val3";

but keys sorting in object by default. In result order next:

X:"val3"
Y:"val2"
Z:"val1"

How does prevent this sorting, that sorting was as had put to original obj?

Upvotes: 0

Views: 44

Answers (1)

Geeky
Geeky

Reputation: 7496

In pure javascript you can do like this

var obj={};
obj.Z = "val1";
obj.Y = "val2";
obj.X = "val3";
var newObj={}

Object.keys(obj)
      .sort()
      .forEach(function(key, value) {
          newObj[key]=obj[key];
       });

console.log(newObj);

Hope this helps

Upvotes: 1

Related Questions