Asked By: Anonymous
Sorry I’m new to vue but I have to create SPA application so I started playing with the code and I’ve been using external API and axios to match dynamic routes in my .vue components for json data like this:
data () {
return {
post: null,
nextPost: null,
prevPost: null,
total: 0,
endpoint: 'https://jsonplaceholder.typicode.com/posts/'
}
},
methods: {
totalPosts (posts) {
this.total = posts
},
getPost (id) {
console.log('currentid' + id)
axios(this.endpoint + id)
.then(response => {
this.post = response.data
})
.catch(error => {
console.log('-----error-------')
console.log(error)
})
},
getNextPost (id) {
if(id === this.total) {
this.nextPost = null
} else {
axios(this.endpoint + (id * 1 + 1))
.then(response => {
console.log(response.data.id)
this.nextPost = response.data
})
.catch(error => {
console.log('-----error-------')
console.log(error)
})
}
},
Now I realised that my application will have to use multiple local json files where each one wil contain a lot of json objects. Application will have to choose file by dynamic route and then to choose object by id in that file.
It can not use any server side language too. So I’m currently lost what would be the best approach here.
Solution
Answered By: Anonymous
this is more of a Javascript question, rather than a Vue question.
when your goal is to select one object from an array of object, .filter() is your friends.
for e.g. https://jsfiddle.net/jacobgoh101/1nv5cesv/3/
if the id you are targeting is 3
axios.get('https://jsonplaceholder.typicode.com/posts/').then(res=>{
const data = res.data;
const sampleId = 3;
const post = data.filter((obj)=>{
return obj.id === sampleId;
}).pop();
console.log(post);
})