Reputation: 1730
I think this is a general Javascipt question however I am working in Vue Js, Laravel & Axios.
How do I push one JSON array into another JSON array? My problem is that when I push the secondary array into the primary array it is nested (see screenshot). I need it as part of the same array.
Is this a simple index issue? I've read concat can achieve this, but I have a "load more" button and wish to append the array and increase the size from the bottom, so push is appropriate. concat creates a new array and replaces current, which isn't desired as I want to maintain the existing array and just increase size for smoother loading of results, like on Pinterest scroll and the new results populated at the bottom.
(this is simplified code to get point across)
Data property empty array to start:
data () {
return {
articles: [],
}
},
Firstly, on page load the articles array is populated with JSON data.
created() {
axios.get(url)
.then(response => {
this.articles = response.data.data;
});
},
Then, I want to 'load more' results via method
loadMore() {
axios.get(url)
.then(response => {
console.log('article\'s array data')
console.log(this.articles)
this.articles.push(response.data.data)
console.log('new response array data')
console.log(response.data.data)
console.log('the updated array with pushed response array')
console.log(this.articles)
});
}
console log
This should be an array of 5 + 5 = 10 for length of articles array if properly appended.
both responses are correct and matching json as I've got it working via concat to merge. But undesirable as it reloads entire array.
Upvotes: 1
Views: 7878
Reputation: 1730
Taken from advice from both @noa-dev and @Shilly above - I used concat as below. Response had to be set in a var for promise as didn't work without. Thanks.
var new_array = response.data.data
this.articles = this.articles.concat(new_array)
Explanation how Vue doesn't actually replace the array when using concat! :) https://v2.vuejs.org/v2/guide/list.html#Replacing-an-Array
Upvotes: 0
Reputation: 3641
If you are against .concat, which is super a very straightforward and performant way, you may try the following:
const myArray = [1,3,4,5];
myArray.push(...[6,7,8,9);
console.log(myArray); // this will contain [1,2,3,4,5,6,7,8,9] now
Upvotes: 4