javascript - 如何对对象数组进行排序?

标签 javascript arrays sorting

我有一个对象数组:

var data= [{
    "title": "All pages",
    "page": "all",

}, {
    "title": "Post with builder",
    "page": "pt_post_6188",

}, {
    "title": "Blog Categories",
    "page": "tx_category",

}, {
    "title": "Single Blog Posts",
    "page": "pt_post",

}];

以及由对象项标题构造的排序顺序数组。

var order = ["Post with builder", "All pages", "Blog Categories", "Single Blog Posts"];

如何按顺序数组对第一个数组进行排序,以便新数据像这样

var newdata= [{
    "title": "Post with builder",
    "page": "pt_post_6188",

}, {
    "title": "All pages",
    "page": "all",

}, {
    "title": "Blog Categories",
    "page": "tx_category",

}, {
    "title": "Single Blog Posts",
    "page": "pt_post",

}];

与引用帖子不同。我按特定顺序数组排序,没有任何特定逻辑。

最佳答案

您可以使用对象作为哈希表

{
    "Post with builder": 0,
    "All pages": 1,
    "Blog Categories": 2,
    "Single Blog Posts": 3
}

获取索引并使用它们进行排序。

var data = [{ "title": "All pages", "page": "all", }, { "title": "Post with builder", "page": "pt_post_6188", }, { "title": "Blog Categories", "page": "tx_category", }, { "title": "Single Blog Posts", "page": "pt_post", }],
    order = ["Post with builder", "All pages", "Blog Categories", "Single Blog Posts"],
    orderObject = {};

order.forEach(function (a, i) {
    orderObject[a] = i;
})

data.sort(function (a, b) {
    return orderObject[a.title] - orderObject[b.title];
});

document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

关于javascript - 如何对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36516676/

相关文章:

javascript - 相当于没有 jQuery 的 $.load

javascript - onClick 函数不会删除数组中的项目

javascript - 对象数组中的子字符串

sql - 如何将 postgres 中的可变长度记录转换为数组?

javascript - 从javascript中的多维数组中获取所有变体

java - 用于计算未正确输出的算法的比较和执行时间的代码

javascript - 用画架保存旋转图像?

javascript - React 应用程序中的意外 token 错误

sorting - Elasticsearch-如何在排序后应用大小

python - 按每个整数的第一个数字对整数列表进行排序