Reputation: 398
Is there a way to sort nested objects by one of their parameters?
For example, if I have a data structure like this:
var someObject = {
'part1328': {
'time': 1543203609575,
},
'part38321': {
'time': 1543203738716,
},
'part1328': {
'time': 1543203746046,
},
'part38338': {
'time': 1543203752264,
}
};
and I don't know how many parts I'll have in advance or what their names will be. Is there a way I can sort the parts by their time and get the most recent and oldest parts?
Upvotes: 1
Views: 168
Reputation: 19070
You can maintain the sorted list by creating an array
sorted by time
Code:
const someObject = {
'part1328': {
'time': 1543203609575,
},
'part38321': {
'time': 1543203738716,
},
'part1328': {
'time': 1543203746046,
},
'part38338': {
'time': 1543203752264,
}
};
const result = Object.keys(someObject)
.sort((a, b) => someObject[a].time - someObject[b].time)
.map(k => ({ [k]: someObject[k] }));
console.log(result);
Upvotes: 0
Reputation: 198314
You cannot sort an object. You can sort a list of object's keys, you can sort object's values, or the list of pairs of a key and a corresponding value ("entries"). Here's the first approach:
Object.keys(someObject).sort((a, b) => a.time - b.time)
// => ["part1328", "part38321", "part38338"]
You can then use these sorted keys to access the values in the original object in the desired order.
Note also that objects can't have repeating keys; they just overwrite each other. Thus, the fourth value is gone even before you assigned it to someObject
.
Upvotes: 1
Reputation: 92440
You can use Object.entries
to get the set of key/value pairs as a list. Then you can sort that list and arrange the data however you like:
var someObject = {
'part1328': {
'time': 1543203609575,
},
'part38321': {
'time': 1543203738716,
},
'part1328': {
'time': 1543203746046,
},
'part38338': {
'time': 1543203752264,
}
};
let arr = Object.entries(someObject).sort((a, b) => a.time - b.time)
console.log(arr)
// from here you can manage the data any way you want.
// for example, an array of simple objects:
let merged = arr.map(([key, value]) => ({id: key, ...value}) )
console.log(merged)
Upvotes: 3