Reverse object with Object.keys and Array.reverse

Viewed 29666

i got the following object

{
  "20170007": {
    "id": 1
  },
  "20170008": {
    "id" : 2
  },
  "20170009": {
   "id": 3
  },
  "20170010": {
    "id": 4
  }
}

desired output:

{
  "20170010": {
    "id": 4
  },
  "20170009": {
   "id": 3
  },
  "20170008": {
    "id" : 2
  },
  "20170007": {
    "id": 1
  }
}

my attempt:

const obj = {
  "20170007": {
    "id": 1
  },
  "20170008": {
    "id" : 2
  },
  "20170009": {
   "id": 3
  },
  "20170010": {
    "id": 4
  }
}

const reverseObj = (obj) => {
  let newObj = {}

  Object.keys(obj)
    .sort()
    .reverse()
    .forEach((key) => {
      console.log(key)
      newObj[key] = obj[key]
    })

  console.log(newObj)
  return newObj  
}

reverseObj(obj)

the wierd part is that when i console.log the key inside the forEach, the keys are reversed. but when i assign the key to the newObj the output is still in the original order... whats going on here ?

EDIT:

thanks for all the responses i took a look into The Map object. Map

new Map([iterable])

Wich was actually i was looking for and the order is guaranteed.

2 Answers
Related