Can I loop through a javascript object in reverse order?

孤街浪徒 提交于 2019-12-03 06:29:09

问题


So I have a JavaScript object like this:

foo = {
  "one": "some",
  "two": "thing",
  "three": "else"
};

I can loop this like:

for (var i in foo) {
  if (foo.hasOwnProperty(i)) {
    // do something
  }
}

Which will loop through the properties in the order of one > two > three.

However sometimes I need to go through in reverse order, so I would like to do the same loop, but three > two > one.

Question:
Is there an "object-reverse" function. If it was an Array, I could reverse or build a new array with unshift but I'm lost with what to do with an object, when I need to reverse-loop it's properties. Any ideas?

Thanks!


回答1:


Javascript objects don't have a guaranteed inherent order, so there doesn't exist a "reverse" order.

4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Browsers do seem to return the properties in the same order they were added to the object, but since this is not standard, you probably shouldn't rely on this behavior.

A simple function that calls a function for each property in reverse order as that given by the browser's for..in, is this:

// f is a function that has the obj as 'this' and the property name as first parameter
function reverseForIn(obj, f) {
  var arr = [];
  for (var key in obj) {
    // add hasOwnPropertyCheck if needed
    arr.push(key);
  }
  for (var i=arr.length-1; i>=0; i--) {
    f.call(obj, arr[i]);
  }
}

//usage
reverseForIn(obj, function(key){ console.log('KEY:', key, 'VALUE:', this[key]); });

Working JsBin: http://jsbin.com/aPoBAbE/1/edit

Again i say that the order of for..in is not guaranteed, so the reverse order is not guaranteed. Use with caution!




回答2:


There is no way to loop through an object backwards, but if you recreate the object in reverse order then you are golden! Be cautions however, there is nothing that says the order of the object will stay the same as it changes and so this may lead to some interesting outcome, but for the most part it works...

function ReverseObject(Obj){
    var TempArr = [];
    var NewObj = [];
    for (var Key in Obj){
        TempArr.push(Key);
    }
    for (var i = TempArr.length-1; i >= 0; i--){
        NewObj[TempArr[i]] = [];
    }
    return NewObj;
}

The just do the swap on your object like this-

MyObject = ReverseObject(MyObject);

The loop would then look like this-

for (var KeysAreNowBackwards in MyObject){
    alert(MyObject[KeysAreNowBackwards]);
} 



回答3:


Why there is no one has mentioned Object.keys() ?

you can get Array of Object's properties ordered as it is, then you can reverse it or filter it as you want with Array methods .

let foo = {
  "one": "some",
  "two": "thing",
  "three": "else"
};

// Get REVERSED Array of Propirties
let properties = Object.keys(foo).reverse();
// "three"
// "two"
// "one"

// Then you could use .forEach / .map
properties.forEach(prop => console.log(`PropertyName: ${prop}, its Value: ${foo[prop]}`));

// PropertyName: three, its Value: else
// PropertyName: two, its Value: thing
// PropertyName: one, its Value: some



回答4:


This answer is similar to a couple of the others, but some users might find the code below easier to copy-paste for their own uses:

Object.keys(foo).reverse().forEach(function(key) { console.log(foo[key]) });

For an object "foo" as described in the question, this code will output the object elements in reverse order: "else", "thing", "some"




回答5:


Just use Object.keys()

This function will take care of it for you:

function loopObject(obj, reverse, logic){
    let keys = reverse? Object.keys(obj).reverse() : Object.keys(obj)
    for(let i=0;i<keys.length;i++){
        logic(obj[keys[i]])
    }
}

Example object:

let my_object = {
    one: 'one',
    two: 'two',
    three: 'three'
}

Loop in order:

loopObject(my_object, false, val => {
    console.log(val) // Insert your logic here.
})

// "one"
// "two"
// "three"

Loop in reverse:

loopObject(my_object, true, val => {
    console.log(val) // Insert your logic here.
})

// "three"
// "two"
// "one"


来源:https://stackoverflow.com/questions/18977881/can-i-loop-through-a-javascript-object-in-reverse-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!