0

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

2
  • 2
    If you need to preserve an order then you need to use an Array; the order of keys in an Object is not guaranteed by design. Commented Jul 11, 2017 at 16:12
  • 2
    There is no key order in JavaScript nor is there a way to enforce one. Commented Jul 11, 2017 at 16:12

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.