I have a question related to JavaScript, specifically in the context of Vue.js, Laravel & Axios.
How can I push one JSON array into another JSON array without nesting it? When I try to push the secondary array into the primary array, it ends up nested (as shown in the screenshot). I need both arrays to be part of the same array structure.
Could this be a simple indexing issue? I've heard that using concat can achieve this, but I prefer to use push because I have a "load more" button and want to append new data to the existing array from the bottom for smoother loading experience, similar to Pinterest's infinite scroll functionality where new results are added at the end.
(Please note that the code provided is simplified for clarity)
I start with an empty array in the data property:
data () {
return {
articles: [],
}
},
Initially, on page load, the articles array gets populated with JSON data.
created() {
axios.get(url)
.then(response => {
this.articles = response.data.data;
});
},
Then, when I want to 'load more' results using a method:
loadMore() {
axios.get(url)
.then(response => {
console.log('Current state of articles array:')
console.log(this.articles)
this.articles.push(response.data.data)
console.log('Newly fetched array data:')
console.log(response.data.data)
console.log('Updated array after pushing new data:')
console.log(this.articles)
});
}
Console log reference link: https://i.sstatic.net/941eM.png
If done correctly, the resulting articles array should have a length of 10 (5 + 5) after appending.
Both responses are accurate and contain valid JSON. I managed to make it work by using concat to merge the arrays. However, I found this method undesirable as it reloads the entire array.