3

I've got a curious situation where I am trying to update an array of objects with a new object, but when I place a console.log statement before the push, it shows that the array already has the new object inside of it. Here is the basics of the code:

 var array1=[{
    "Name": "Lake",
    "ID": "1234"
    }];

var object1={
    "Name": "Mountain",
    "ID": "1234"
    };

function testArray() {
    console.log(array1);
    array1.push(object1);

    }

I'd eventually like to update the original array with new information if the object contains the same ID. If it does not contain the same ID, then it should be appended. This would happen with an $.each loop over array1.

I'd greatly appreciate any help. Thank you.

1 Answers1

2

It is because you are doing this in a webkit broswer like Chrome and console.log() is being queued up (it's a webkit bug, it won't happen if you do it in Firefox or non-webkit broswer), and therefore it prints a later value of the array. You need to use

JSON.stringify(array1);

for a more accurate result.

If you want to update the original array with new information only when the object contains the same ID, use an if statement to check the ID:

function updateA(obj){
  if(obj.ID === array1.ID){
    array1.push(obj); 
    console.log( JSON.stringify(array1));
  }
}
updateA(object1);
Archy Will He 何魏奇
  • 9,589
  • 4
  • 34
  • 50
  • This is happening in Safari actually. Not sure if it's a webkit issue or not... – Lang Schwartzwald Oct 01 '13 at 00:31
  • @LangSchwartzwald Yup it's actually a webkit issue.. – Archy Will He 何魏奇 Oct 01 '13 at 00:34
  • 1
    Yup, this is a well know issue seen in some browsers. `console.log()` gets queued up. The work-around is to stringify the output before passing it to `console.log()`. Since strings are invariant, this problem does not happen with strings. This only happens when you pass an object or array reference that then gets changed immediately (before the browser gets around to logging the info to the console). – jfriend00 Oct 01 '13 at 00:41
  • Still exists in 2023...testing on Chrome and Safari – Harizul Jan 16 '23 at 08:05