Reputation: 405
I have an array articles
that has arrays results
. I am attempting to combine all these results into one array without the results
for example:
const articles = [{ "id": 203, "title": "testing"}, {"id": 213,"title": "new title"}, { "id": 1, "title": "one"}, {"id": 2,"title": "two"}, { "id": 32, "title": "test article"}, {"id": 62,"title": "title test"}]
I've attempted to achieve this by mapping articles
but the return result are still separate arrays instead of 1 array of objects. How can I achieve this?
Here is my code snippet:
const articles = [{results: [{ "id": 203, "title": "testing"}, {"id": 213,"title": "new title"}]}, {results: [{ "id": 1, "title": "one"}, {"id": 2,"title": "two"}]}, {results: [{"id": 62,"title": "title test"}]} ]
let mappedArticles = articles.map(article => {
return article.results
})
console.log(mappedArticles)
Upvotes: 0
Views: 41
Reputation: 23654
You can use flatMap
const articles = [{results: [{ "id": 203, "title": "testing"}, {"id": 213,"title": "new title"}]}, {results: [{ "id": 1, "title": "one"}, {"id": 2,"title": "two"}]}, {results: [{"id": 62,"title": "title test"}]} ]
let mappedArticles = articles.flatMap(article => article.results)
console.log(mappedArticles)
Upvotes: 3
Reputation: 399
In case flatMap
is not supported by your environment, there is another way to achieve it, although a bit more verbose and non-trivial, which uses the concat method of the Array prototype:
const articles = [{results: [{ "id": 203, "title": "testing"}, {"id": 213,"title": "new title"}]}, {results: [{ "id": 1, "title": "one"}, {"id": 2,"title": "two"}]}, {results: [{"id": 62,"title": "title test"}]} ]
const mappedArticles = articles.reduce((acc, article) => acc.concat(article.results), []);
console.log(mappedArticles);
Upvotes: 0