Can I loop through a javascript object in reverse order?

后端 未结 4 772
感情败类
感情败类 2021-02-03 17:44

So I have a JavaScript object like this:

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

I can loop this like:

4条回答
  •  我在风中等你
    2021-02-03 18:24

    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

提交回复
热议问题