How can I iterate over object attributes back in javascript?

For example, I already have an object filled with ordered key values, I can iterate its keys forward using the instructions for :

var keyvalues = {"key1":"value1","key2":"value2","key3":"value3"}; for(var key in keyvalues) { var value = keyvalues[key]; ............. } 

Now I want to iterate back keys such as "key3", "key2", "key1", is there a magic way to do this?

+4
source share
2 answers

There is no guarantee of order for... in loop.

Wait what?

There is no logic in the "order" of object keys. If you want, you can capture them, then use .sort on them. The language specification explicitly talks about this in the for...in iterative algorithm:

The mechanics and order of listing properties (step 6.a in the first algorithm, step 7.a in the second) is not indicated.

What are your options:

In JavaScript, most ordered timelists are represented by arrays . You can create an array for us if this is an ordered list in your case:

 var values= ["key1","key2","key3"]; for(var i=0;i<values.length;i++){ values[i];// order is guaranteed here. } 

Since order is guaranteed, you can also easily reverse it:

 var values= ["key1","key2","key3"].reverse();//reverse is an array method for(var i=0;i<values.length;i++){ values[i];// order is guaranteed here. } 

If you already have an object , you can take its keys and .sort them based on some criterion, for example, in lexicographic order:

 var obj = {"key1":"value1","key2":"value2","key3":"value3"}; var keys = Object.keys(obj).sort().reverse(); // see note for(var i=0;i<keys.length;i++){ console.log(keys[i]); } // will output key3, key2, key1 

note: you can pass the .sort comparator and cancel it for you instead of chaining, which is probably better. I kept it for pedagogical purposes.

+9
source

You can use var keys = Objects.keys(keyvalues).sort() to get all the keys of an object, and then just iterate through it backwords in a for(int = keys.length;i>0;i--) loop for(int = keys.length;i>0;i--) , addressing to the source object, for example, value = object[keys[i]] in a loop

EDIT: Added a call to the sort function in the array of keys returned by Object.keys .

+2
source

Source: https://habr.com/ru/post/1490968/


All Articles