elpha01
elpha01

Reputation: 306

Cannot stringify an array of object in JS

I am going crazy on Javascript because I can't make JSON.stringify works with a simple array of object. I have searched for similar problem on google and nothing solved my problem.

Here is the code:

console.log(array);
console.log(typeof array);
console.log(Array.isArray(array));
console.log(JSON.stringify(array));

Here the output:

Console output

So the first line is correct, this is an array of object. The second line is for me false but it seems to be correct because of Javascript. Third line is correct. Fourth line is incorrect, the array is stringified as an empty object?

I have probably missed a stupid thing but I really can't figure what.

Thank you

EDIT: Here how I globally create the array previously

var array = [];
...
array.push(obj);

EDIT2: Complete code

sendCameras= function(cameraArray){
                var message = {};
                message.cameras =  cameraArray;
                console.log("----------------");
                console.log(cameraArray);
                console.log(typeof cameraArray);
                console.log(Array.isArray( cameraArray));
                console.log(cameraArray.length);
                console.log(JSON.stringify({cameraArray:Array}));
                event.source.postMessage(JSON.stringify(message), event.origin);
            }

The second part of the code that calls the previous function:

openCamerasByNames= function(cameras){
var cameraToOpen = [];
var openCamerasByIdFromNames =function (){
    external_bloc :for (let i  = 0; i < cameras.length; i++){
        internal_bloc :for (let j  = 0; j  < cameraList.cameras.length; j++){
            if (cameraList.cameras[j].name == cameras[i].name){
                openCameraById(cameraList.cameras[j].id);
                cameraToOpen.push(cameraList.cameras[j]);
                break internal_bloc;
            }
        }
    }
}
sendCameras(cameraToOpen);
...

EDIT3: cameraList is created from JSON.parse

Upvotes: 0

Views: 1608

Answers (2)

elpha01
elpha01

Reputation: 306

I fixed my problem but I absolutely don't know how the output could show this.

the sendCameras call was not at the good position, it has to be at the end of openCamerasByIdFromNames otherwise the sendCameras will be called before push. But I don't understand how could the output show the array with one element.

Upvotes: 0

George
George

Reputation: 2422

You are stringifying an object {}, not the actual array.

let cameraArray = [{myObj:"some content"}];

//wrong
console.log(JSON.stringify({cameraArray:Array}));
console.log("array? ", Array.isArray({cameraArray:Array}));

//right
console.log(JSON.stringify(cameraArray));
console.log("array? ", Array.isArray(cameraArray));

Upvotes: 1

Related Questions