-2

I am trying to create an object that looks something like this:

{
    '2017': 2017,
    '2016': 2016,
    '2015': 2015,
    '2014': 2014
}

But for whatever reason, it keeps outputting me ascending order instead:

const EXAMPLE = () => {
    const exampleObj = {}

    for (let year = 2017; year >= 2014; year--) {
        exampleObj[year] = year
    }   


    return exampleObj
}

let example = EXAMPLE()
console.log(example)

Is it possible to achieve of what I desire in Javacript? I would choose Map but in my application, I need an object to render a certain component

Alejandro
  • 1,906
  • 4
  • 27
  • 58
  • 2
    order in objects is not guarantee: https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – quirimmo May 26 '17 at 16:43
  • Don't use an object if you need sorting. – Heretic Monkey May 26 '17 at 16:43
  • Possible duplicate of [Does JavaScript Guarantee Object Property Order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – quirimmo May 26 '17 at 16:45
  • Actually, it's a dupe of [Sort JavaScript object by key](https://stackoverflow.com/q/5467129/215552). It's possible in ES6/ES2015. – Heretic Monkey May 26 '17 at 16:50
  • yes actually I was looking for a link where they show how to use Map, but cannot find it btw: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map – quirimmo May 26 '17 at 16:52
  • "I need an object to render a certain component" what does this mean? – Nick May 26 '17 at 16:58

1 Answers1

0

No, this is not possible to achieve when you use an Object's keys. You should use a Map instead.

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.

Mateusz Kleinert
  • 1,128
  • 9
  • 18