根据值对Javascript对象进行排序 [英] Sort a Javascript object based on value

查看:74
本文介绍了根据值对Javascript对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个json对象:

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

}

是否可以根据其位置编号对其进行排序,而无需将其转换为数组?我尝试将其转换,但它更改了格式(它删除了名称,类型,id,键),但我不希望这样做.它应该保持原样(格式),但要根据其位置而定.

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.

我做了什么:

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

推荐答案

与问题的第一个注释相一致,您应该将对象替换为数组并删除冗余.位置将由数组中元素的位置确定,并且元素的键将不再与id属性重复

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

使用此代码,您可以对对象进行排序,但是您不能将id用作键,因为否则它将再次按字母顺序而不是位置进行排序.

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)

这篇关于根据值对Javascript对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆