Answer the question
In order to leave comments, you need to log in
How to display related data from two arrays in Vue?
I make requests through axios and get two arrays
Users, Posts
Users
Posts
But the data of these arrays are linked by userId
I need to display all the records from the arrays on the page. Title, text and author's name
The title and text(body) are taken from the posts array
The author's name(name) is taken from the users array
How can I link these arrays and display their data?
Here is what is currently available:
<b-container fluid="lg" class="mt-lg-5">
<b-row class="d-flex justify-content-center">
<b-col sm="4" v-for="(post) in posts" :key="post.id">
<b-card class="text-left mb-4">
<b-card-text class="text-primary font-weight-bolder">
{{post.title}}
</b-card-text>
<b-card-text>
{{post.body}}
</b-card-text>
<b-card-text class="mt-5 font-weight-bold text-black-50">
author
</b-card-text>
</b-card>
</b-col>
</b-row>
</b-container>
created() {
this.getAllPosts();
this.getAllUsers();
},
methods: {
async getAllPosts() {
await axios.get('http://jsonplaceholder.typicode.com/posts')
.then(response => {
this.posts = response.data
})
.catch(error => {
console.log(error)
})
},
async getAllUsers() {
await axios.get('http://jsonplaceholder.typicode.com/users')
.then(response => {
this.users = response.data
console.log(this.users)
})
.catch(error => {
console.log(error)
})
},
}
Answer the question
In order to leave comments, you need to log in
Well, ideally. You could theoretically receive posts from the database, immediately indicating the author, for example.
Well, okay. There are several options.
You can tweak the this.posts array when getting users:
async getAllUsers() {
const { data: users } = await axios.get('http://jsonplaceholder.typicode.com/users')
this.posts = this.posts.map(p => {
p.author = users.find(u => u.id === p.userId)
return p
})
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question