Reputation: 93
I am trying to sort through some JSON by highest amount to lowest with some nested values. Take the following object:
"videos": {
"0": {
"video_name": "Calls",
"video_filename": "ALEXA_CALLS.mp4",
"count": 1
},
"1": {
"video_name": "Routines",
"video_filename": "ROUTINES.mp4",
"count": 3
},
"4": {
"video_name": "Photos",
"video_filename": "PHOTOS.mp4",
"count": 4
}
}
Is it possible to sort through this based on the 'count value', so the Photos would be the first property, then Routines, etc. Sort of like this:
"videos": {
"4": {
"video_name": "Photos",
"video_filename": "PHOTOS.mp4",
"count": 4
},
"1": {
"video_name": "Routines",
"video_filename": "ROUTINES.mp4",
"count": 3
},
"0": {
"video_name": "Calls",
"video_filename": "ALEXA_CALLS.mp4",
"count": 1
},
}
I've seen from other questions that you can sort if you convert the json object into an array and do something with .sort, but it seems the numbers "0", "1", "4", etc can cause issues as I can't figure out how to generically reference the whole object. With other stuff I am doing, I need to do stuff like videos[0].video_name.
Anyone seen something like this before? Any tips would be great !
Update with example:
let v = {
"0": {
"video_name": "Calls",
"video_filename": "ALEXA_CALLS.mp4",
"count": 1
},
"1": {
"video_name": "Routines",
"video_filename": "ROUTINES.mp4",
"count": 3
},
"4": {
"video_name": "Photos",
"video_filename": "PHOTOS.mp4",
"count": 4
}
};
v.sort(function(a, b) {
return a.count > b.count;
});
console.log(v);
Upvotes: 1
Views: 1734
Reputation: 541
First your data isn't quite JSON; it should be wrapped in another set of brackets like
{
"videos": {
"4": {
"video_name": "Photos",
"video_filename": "PHOTOS.mp4",
"count": 4
},
"1": {
"video_name": "Routines",
"video_filename": "ROUTINES.mp4",
"count": 3
},
"0": {
"video_name": "Calls",
"video_filename": "ALEXA_CALLS.mp4",
"count": 1
}
}
}
From there you can parse it, grab out the values and sort via
const data = JSON.parse(...)
Object.values(data.videos).sort((a,b) => a.count - b.count)
Also, you can reverse the sort by reversing the body of the sort function
(a,b) => b.count - a.count
Upvotes: 1
Reputation: 414
You can do it by converting it to an array
const obj = {
"videos": {
"0": {
"video_name": "Calls",
"video_filename": "ALEXA_CALLS.mp4",
"count": 1
},
"1": {
"video_name": "Routines",
"video_filename": "ROUTINES.mp4",
"count": 3
},
"4": {
"video_name": "Photos",
"video_filename": "PHOTOS.mp4",
"count": 4
}
}
}
const videos = obj.videos
const videoArray = Object.entries(videos).map(([key, value]) => ({...value, key: key}))
const sortedVideoArray = videoArray.sort((a, b) => b.count - a.count)
console.log(sortedVideoArray)
there is no point in putting the values from the array back into an object since js objects do not guarantee that they will maintain insert order but that code snippet above does allow you to maintain which video had which key in the object
Upvotes: 3