I created an array of random values below:
const maxNumber = 120;
const arrayNumber = [];
for (let i=0; i<12;i++){
const randomNumber = Math.floor((Math.random() * maxNumber) + 1);
arrayNumber.push ( randomNumber )
}
I now want to display 12 random posts, how should I pass the arrayNumber value that I have created.
I generally use below code to fetch nodes
data.allWordpressPost.edges[0].node.title
data.allWordpressPost.edges[1].node.title
data.allWordpressPost.edges[2].node.title
but now I want to pass arrayNumber values, I tried below code but it won’t work
data.allWordpressPost.edges[arrayNumber[0]].node.title
data.allWordpressPost.edges[arrayNumber[1]].node.title
data.allWordpressPost.edges[arrayNumber[2]].node.title
what is the correct way, please advise.
Please explain what you’re actually doing: you’re using some kind of directed graph library but you haven’t specified what it is. You’re asking people to guess what {library|database|thing} you’re programming against, we can’t read your mind.
I am using gatsbyjs with WordPress and Graphql.
The one you are trying, with the random numbers, should be exactly the same as the one you normally try, just with different numbers. You are putting a number in as an edge, same thing. So
What won’t work? What are the errors? What is the value arrayNumber
in your code at the point it is used? What is different about the code, and does it work if you just hardcode numbers in to check it?
When I use below code it works:
data.allWordpressPost.edges[0].node.title
data.allWordpressPost.edges[1].node.title
data.allWordpressPost.edges[2].node.title
But I want to pass dynamic values instead of 0, 1, 2 indexes. That’s why I am generating random number but I don’t know how to pass this arrayNumber values as index for above code.
Seems like you might need a refresher in accessing objects.
Accessing Object Properties with Variables
@RandellDawsonThank you so much, it really helped and I was able to solve my issue by storing the values in another temporary variable and then using its values for index value.
const tempOne = arrayNumber[1]
data.allWordpressPost.edges[tempOne].node.title