Muthuraman Sundararaj
Muthuraman Sundararaj

Reputation: 311

JavaScript - Maintain Object key value order

My required object key-value(property-value) Order : {three:3,two:2,one:1}

I want last added key at top,When i add key-value dynamically the order i got is given below,

var numObj={};   
numObj["one"]=1;   
numObj["two"]=2; 
numObj["three"]=3;  
console.log(numObj) // result i get is  { one:1, three:3,two:2 } 

Please any one help me to get this key-value order {three:3,two:2,one:1}

enter image description here

Upvotes: 0

Views: 838

Answers (1)

Adam Wright
Adam Wright

Reputation: 49376

As the commenters point out, JavaScript objects have no defined order for iteration. However, JavaScript maps do: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map.

let aMap = new Map();
myMap.set('AKey1', 'AValue1');
myMap.set('AKey2', 'AValue2');
myMap.set('AKey3', 'AValue3');

for (let x of aMap) {
  console.log(x[1]);
}

Will provide

AValue1
AValue2
AValue3

Upvotes: 2

Related Questions