Reputation: 161
Hi there guys I am new in this but I have a array in my localstorage I get that array I save in old empty array, and I make a petition to the ajax and I try push the new data into my old array
$.getJSON(setUrl(pagination, page), function (response) {
var old = [];
old = JSON.parse(localStorage.getItem('msg'));
old.push(response.DATA);
console.log(old);
});
but the result I getting is some like this
I put all my new array inside a index of my old array what am I doing wrong ? can some one help me
Upvotes: 0
Views: 76
Reputation: 38757
Use Array.ptototype.concat() instead to merge the arrays.
Array.prototype.concat()
:
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
$.getJSON(setUrl(pagination, page), function (response) {
var old = [];
old = JSON.parse(localStorage.getItem('msg'));
old = old.concat(response.DATA);
console.log(old);
});
var old = [
{ id: 1 },
{ id: 2 }
];
console.log('old: ', old);
var json = [
{ id: 3 },
{ id: 4 }
];
old = old.concat(json);
console.log('merged: ', old);
Hopefully that helps!
Upvotes: 1
Reputation: 136094
You have to use concat
but remember....
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. source
$.getJSON(setUrl(pagination, page), function (response) {
var old = [];
old = JSON.parse(localStorage.getItem('msg'));
var combined = old.concat(response.DATA);
console.log(combined);
});
Upvotes: 1