我有一组对象:
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",
}];和参考文献不一样。我是按特定的顺序数组进行排序,没有任何特定的逻辑。
发布于 2016-04-09 12:36:51
您可以使用对象作为哈希表。
{
"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>');
发布于 2016-04-10 16:22:07
由于您已经将订单数组索引作为一种散列来用于您的订单引用,所以我们可以非常简单地使用它们;
sorted = Array(order.length);
data.forEach((c,i) => sorted[order.indexOf(c.title)] = c);发布于 2016-04-11 18:44:00
//使用负载
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类别“、"Single Blog Post”;
function (data, order){
return _.reduce(order, function (output, v) {
output.push(_.filter(data,{title:v})[0]);
return output;
},[]);
}https://stackoverflow.com/questions/36516676
复制相似问题