Sort a Javascript object based on value [duplicate]

烂漫一生 提交于 2021-01-27 18:23:34

问题


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);

回答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)


来源:https://stackoverflow.com/questions/48081768/sort-a-javascript-object-based-on-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!