使用JavaScript对对象进行排序和数组

使用JavaScript对对象进行排序和数组,javascript,arrays,Javascript,Arrays,我有以下数组,需要按国家/地区按字母顺序排序: data=[ { "country": "China", "brands": { "abc": "123", "def": "123", }, "day": "2020-04-16", "time": "2020-04-16T14:30:05+00:00" }, { "country

我有以下数组,需要按国家/地区按字母顺序排序:

data=[
    {
        "country": "China",
        "brands": {
            "abc": "123",
            "def": "123",
        },
        "day": "2020-04-16",
        "time": "2020-04-16T14:30:05+00:00"
    },
    {
        "country": "Zimbawe",
        "brands": {
            "abc": "123",
            "def": "123",
        },
        "day": "2020-04-16",
        "time": "2020-04-16T14:30:05+00:00"
    },
    {
        "country": "Africa",
        "brands": {
            "abc": "123",
            "def": "123",
        },
        "day": "2020-04-16",
        "time": "2020-04-16T14:30:05+00:00"
    }
]
到目前为止,我已经试过了:

data.sort()
还有:

function(a, b){return a - b}

但它仍然返回与原始数组相同的顺序。那么,如何使用国家作为基础对其进行排序呢?

您可以使用
排序功能

 data.sort(function(a, b){
   var countryA=a.country.toLowerCase(), countryB=b.country.toLowerCase();
  if (countryA < countryB)
    return -1;
  if (countryA > countryB)
    return 1; 
});
data.sort(函数(a,b){
var countryA=a.country.toLowerCase(),countryB=b.country.toLowerCase();
如果(国家A<国家B)
返回-1;
如果(countryA>countryB)
返回1;
});

使用
排序
方法

const data=[{“国家”:“中国”,“品牌”:{“abc”:“123”,“def”:“123”,},“日期”:“2020-04-16”,“时间”:“2020-04-16T14:30:05+00:00”},{“国家”:“Zimbawe”,“品牌”:{“abc”:“123”,“def”:“123”,},“日期”:“2020-04-16”,“时间”:“2020-04-16T14:30:05+00”},{“国家”:“非洲”,“品牌”:“abc”:“123”,“def”:“123”,},“日期”:“2020-04-16:00:00”“2020-04-16T14:30:05+00:00”};
数据排序((a,b)=>a.country>b.country?1:-1);
console.log(数据);

。作为控制台包装{min height:100%!important;top:0;}
FYI,多维数组将数组作为元素,而不是对象。