I have the graphQL query with the following schema:
export const ALL_BOOKS = gql`
query {
allBooks {
title
published
author {
name
born
}
id
genres
}
}
I have passed this result to a react component through props. I am trying to get the genres of each book and store it in an array of a single dimension. To me, it makes perfect sense to write:
let genres = props.books.map(book => (...book.genres))
Why does this code not work? What is wrong with returning an object with the spread operator and what alternative do you think would work to return books>book>genres>genre into a single array. I really want to avoid the nested-for-loop thing.
Thanks!
Input structure is like so:
0: {__typename: 'Book', title: 'Book1', published: 2022, author:
{…}, id: '61d5e02beef9d5fcdb5ce26b', …}
1: {__typename: 'Book', title: 'Book2', published: 2022, author:
{…}, id: '61d5e061eef9d5fcdb5ce270', …}
2: {__typename: 'Book', title: 'Book3', published: 2022, author:
{…}, id: '61d5e07a3473e9ac212f87dc', …}
Taken from console log
-- With Stringfy
[
{
"__typename": "Book",
"title": "The Key of Solomon",
"published": 2022,
"author": {
"__typename": "Author",
"name": "Steve Jobs",
"born": 1999
},
"id": "61d5e02beef9d5fcdb5ce26b",
"genres": [
"Philosophy",
"Witchcraft"
]
},
{
"__typename": "Book",
"title": "The Steez of Solomon",
"published": 2022,
"author": {
"__typename": "Author",
"name": "Horace Gumdrop",
"born": 1998
},
"id": "61d5e061eef9d5fcdb5ce270",
"genres": [
"Philosophy",
"Steezcraft"
]
},
{
"__typename": "Book",
"title": "The Steep",
"published": 2022,
"author": {
"__typename": "Author",
"name": "Bulhar",
"born": null
},
"id": "61d5e07a3473e9ac212f87dc",
"genres": [
"Philosophy",
"Steezcraft"
]
}
]
Try this
let genres = props.books.map(book => ({...book.genres}))
From your question, it seems that you only want to return the genres:
let genres = props.books.map(book => book.genres)
This will return an array with the genres extracted from the books prop
Later edit: your question was unclear, but probably you want to get the entire list of genres from each genres sublist AND remove duplicates:
let genres = props.books.map(book => book.genres).flat().reduce((arr, elem) => {
if(arr.indexOf(elem) === -1) {
arr.push(elem);
}
return arr;
}, []);