0

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

enter image description here

I put all my new array inside a index of my old array what am I doing wrong ? can some one help me

  • This happens when response.DATA is an array. This is behaving as expected. If you want to add each item individually, iterate over them. – Bucket Nov 15 '18 at 16:16
  • possible duplicate of https://stackoverflow.com/questions/1374126/how-to-extend-an-existing-javascript-array-with-another-array-without-creating – Tanmay Nov 15 '18 at 16:33

2 Answers2

1

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!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
1

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);
});
Jamiec
  • 133,658
  • 13
  • 134
  • 193