The elements of an object do not have an order
If you want them to have an order, you should store the elements in an array.
const obj = {
"20170007": {
"id": 1
},
"20170008": {
"id" : 2
},
"20170009": {
"id": 3
},
"20170010": {
"id": 4
}
}
const arrayReverseObj = (obj) => {
let newArray = []
Object.keys(obj)
.sort()
.reverse()
.forEach(key => {
console.log(key)
newArray.push( {
'key':key,
'id':obj[key].id
})
})
console.log(newArray)
return newArray
}
arrayReverseObj(obj)
The result is similar to what you want, but is an array (so that the elements can have an order):
[{
"key": "20170010",
"id": 4
},
{
"key": "20170009",
"id": 3
},
{
"key": "20170008",
"id": 2
},
{
"key": "20170007",
"id": 1
}]
Being more concise, using .map
Instead of exactly mirroring your code layout, we could use .map()
as indicated in the comment below. An example would be:
const arrayReverseObj =
obj => Object.keys(obj).sort().reverse().map(key=> ({key:key,id:obj[key].id}) );
If you want the whole of each sub-object, not just the `id` property
As pointed out in the further comment below,
const arrayReverseObj =
obj => Object.keys(obj).sort().reverse().map(key=> ({...obj[key],key:key}) );
This returns an array of objects, in reverse-sorted order of their key, and with each object having an extra property key
containing their key.
In general, for any object o
, the {... o }
construction is creating a new object, composed of all the properties of o
, i.e. a kind of duplicate of o
. {... o, foo:"bar" }
does the same, but adds a new property foo
with value "bar".
Therefore we are unbundling ("destructuring") the original sub-object, merging in a new property key
, and then rebundling it into a new object which is like the original, but with the extra property.
This achieves the same as Object.assign
but is declarative (functional) rather than imperative (procedural), which makes it easier to read.
A further shorthand also suggested by a commenter is that when you are building an object with an expression like { a: 1, b: "hello", c: c }
, in the case of the property c
whose value is being set to a variable that is also called c
, you can just skip the : c
, and Javascript will assume you mean c: c
. Therefore it saves space to write { a: 1, b: "hello", c }
.
So our statement would become:
const arrayReverseObj =
obj => Object.keys(obj).sort().reverse().map(key=> ({ ...obj[key], key }) );