Reputation: 355
I use an api which returns an object 'results'. The 'results' object holds other objects which have type article or detail.
Each one of the the result (article or detail) contain their own object results with different pages of that type.
What i want to do: store the results in an array 'pages' where i order them by all the articles first then all the details
I want to sort them in the array because I need to display the articles first then the detail pages in the frontend.
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);
});
}
});
This was my attempt with Lodash find but in the frontend i still have results where the details are displayed after the articles.
Note: The api result can be like this: {detail}, {article} but also like this {detail}, {article}, {detail}, {article}
Sample data:
results: [
{
type: 'article',
results: {
{
title: '',
body: '',
...
},
...
}
},
{
type: 'detail',
results: {
{
title: '',
body: '',
...
},
...
}
},
...
]
Upvotes: 0
Views: 331
Reputation:
After a long dicussion :
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));
Upvotes: 1