我有一个对象数组:
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/