Sort A Javascript Object Based On Value
I have this json object: obj = { 'name': { 'display': 'Name', 'id': 'name', 'position': 3 }, 'type': { 'id': 'type',
Solution 1:
In agreement with the first comments of your question, you should replace your object with an array and remove the redundancies. The position will be determined by that of the element in the array and the keys of your elements will no longer be duplicated with your id properties
EDIT: With this code you can sort the object but you can't use id as key because otherwise it will be sorted again alphabetically instead of position.
let obj = {
"name":
{
"display": "Name",
"id": "name",
"position": 3
},
"type":
{
"id": "type",
"position": 0
},
"id":
{
"display": "ID",
"id": "id",
"position": 1
},
"key":
{
"display": "Key",
"id": "key",
"position": 2
},
}
let arr = [];
for(let i in obj) {
if(obj.hasOwnProperty(i)) {
arr[obj[i].position] = obj[i]
}
}
let sortedObj = {};
for(let i in arr) {
sortedObj[i] = arr[i]
}
console.log(sortedObj)
Post a Comment for "Sort A Javascript Object Based On Value"