Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array becomes an object structure

I'm experiencing an odd behavior (maybe it isn't odd at all but just me not understanding why) with an javascript array containing some objects.

Since I'm no javascript pro, there might very well be clear explanation as to why this is happening, I just don't know it.

I have javascript that is running in a document. It makes an array of objects similar to this:

var myArray = [{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...];

If I print out this array at the place it was created like JSON.stringify(myArray), I get what I was expecting:

[{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...]

However, if I try to access this array from a child document to this document (a document in a window opened by the first document) the array isn't an array any more. So doing JSON.stringify(parent.opener.myArray) in the child document will result in the following:

{"0":{"Id":"guid1","Name":"name1"},"1":{"Id":"guid2","Name":"name2"},...}

And this was not what I was expecting - I was expecting to get the same as I did in teh parent document.

Can anyone explain to me why this is happening and how to fix it so that the array is still an array when addressed from a child window/document?

PS. the objects aren't added to the array as stated above, they are added like this:

function objTemp()
{
    this.Id = '';
    this.Name = '';
};

var myArray = [];

var obj = new ObjTemp();
obj.Id = 'guid1';
obj.Name = 'name1';

myArray[myArray.length] = obj;

If that makes any difference.

Any help would be much appreciated, both for fixing my problem but also for better understanding what is going on :)

like image 628
Aidal Avatar asked May 02 '12 09:05

Aidal


2 Answers

The very last line might be causing the problem, have you tried replacing myArray[myArray.length] = obj; with myArray.push(obj);? Could be that, since you're creating a new index explicitly, the Array is turned into an object... though I'm just guessing here. Could you add the code used by the child document that retrieves myArray ?

Edit

Ignore the above, since it won't make any difference. Though, without wanting to boast, I was thinking along the right lines. My idea was that, by only using proprietary array methods, the interpreter would see that as clues as to the type of myArray. The thing is: myArray is an array, as far as the parent document is concerned, but since you're passing the Array from one document to another, here's what happens:

An array is an object, complete with it's own prototype and methods. By passing it to another document, you're passing the entire Array object (value and prototype) as one object to the child document. In passing the variable between documents, you're effectively creating a copy of the variable (the only time JavaScript copies the values of a var). Since an array is an object, all of its properties (and prototype methods/properties) are copied to a 'nameless' instance of the Object object. Something along the lines of var copy = new Object(toCopy.constructor(toCopy.valueOf())); is happening... the easiest way around this, IMO, is to stringency the array withing the parent context, because there, the interpreter knows it's an array:

//parent document
function getTheArray(){ return JSON.stringify(myArray);}
//child document:
myArray = JSON.parse(parent.getTheArray());

In this example, the var is stringified in the context that still treats myArray as a true JavaScript array, so the resulting string will be what you'd expect. In passing the JSON encoded string from one document to another, it will remain unchanged and therefore the JSON.parse() will give you an exact copy of the myArray variable.

Note that this is just another wild stab in the dark, but I have given it a bit more thought, now. If I'm wrong about this, feel free to correct me... I'm always happy to learn. If this turns out to be true, let me know, too, as this will undoubtedly prove a pitfall for me sooner or later

like image 50
Elias Van Ootegem Avatar answered Oct 01 '22 02:10

Elias Van Ootegem


Check out the end of this article http://www.karmagination.com/blog/2009/07/29/javascript-kung-fu-object-array-and-literals/ for an example of this behavior and explanation.

Basically it comes down to Array being a native type and each frame having its own set of natives and variables.

From the article:

// in parent window
var a = [];
var b = {};
//inside the iframe
console.log(parent.window.a); // returns array
console.log(parent.window.b); // returns object

alert(parent.window.a instanceof Array); // false
alert(parent.window.b instanceof Object); // false
alert(parent.window.a.constructor === Array); // false
alert(parent.window.b.constructor === Object); // false

Your call to JSON.stringify actually executes the following check (from the json.js source), which seems to be failing to specify it as an Array:

        // Is the value an array?
        if (Object.prototype.toString.apply(value) === '[object Array]') {
           //stringify
like image 28
nvuono Avatar answered Oct 01 '22 04:10

nvuono