2

I have this json object:

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
    },

}

Is it possible to sort it based on their position numbers, without converting it to an array? I tried to convert it but it changes the format (it deletes the name,type,id,key) and I don't want this.. It should stay as it is (the format) but just in order based on their position.

what i did:

var array = $.map(obj, function(value, index) {
            return [value];
        });

        array.sort(function(a,b){
            return a.position - b.position;
        });
        obj= JSON.stringify(array);
        obj= JSON.parse(obj);
johnmmm
  • 105
  • 11

1 Answers1

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)
Alex83690
  • 650
  • 7
  • 24