我使用一个返回对象“结果”的 API。 “结果”对象包含具有文章或详细信息类型的其他对象。
每个结果(文章或详细信息)都包含自己的对象结果以及该类型的不同页面。
我想要做的:将结果存储在数组“pages”中,我首先按所有文章排序,然后按所有详细信息排序
我想在数组中对它们进行排序,因为我需要先显示文章,然后在前端显示详细信息页面。
var pages = [];
_.find(results, function(r) {
if(r.type === 'article') {
_.forEach(r.results, function(p) {
p.type = 'article';
pages.push(r);
});
} else if(r.app === 'detail') {
_.forEach(r.results, function(p) {
p.type = 'detail';
pages.push(p);
});
}
});
这是我对 Lodash find 的尝试,但在前端我仍然有结果,详细信息显示在文章后面。
注意:api结果可以是这样的:{detail},{article},也可以这样{detail},{article},{detail},{article}
示例数据:
results: [
{
type: 'article',
results: {
{
title: '',
body: '',
...
},
...
}
},
{
type: 'detail',
results: {
{
title: '',
body: '',
...
},
...
}
},
...
]
最佳答案
经过长时间的讨论:
var sorted;
var articles = [];
var details = [];
var source = [{
app: "article",
results: [
{ title: "a" },
{ title: "b" },
{ title: "c" }
]
}, {
app: "detail",
results: [
{ title: "d" },
{ title: "e" },
{ title: "f" }
]
}, {
app: "article",
results: [
{ title: "g" },
{ title: "h" },
{ title: "i" }
]
}];
for (var i = 0; i < source.length; i++) {
switch (source[i].app) {
case "article": articles = articles.concat(source[i].results); break;
case "detail": details = details.concat(source[i].results); break;
}
}
sorted = articles.concat(details);
console.log("articles =", JSON.stringify(articles));
console.log("details =", JSON.stringify(details));
console.log("sorted =", JSON.stringify(sorted));
console.log("source =", JSON.stringify(source));
关于javascript - 使用 lodash find 推送到数组时按值对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408366/