首页 > 解决方案 > JSON.stringify not working with nested array in javascript

问题描述

I am trying to JSON.stringify(docArray) which contains a nested array in the object that is not being stringified.

console.log(docArray); - returns the information below

(3) [{…}, {…}, {…}]
0:
 docName: "name"
 refDoc: Array(3)
   0: "doc1"
   1: "doc2"
   2: "doc3"
   length: 3
   __proto__: Array(0)
 __proto__: Object

When I stringify the object I receive the following :

console.log(JSON.stringfy(docArray));

[{"docName:"name","refDoc":[]},

Javascript to create the docArray:

docArray = [];
for(let i = 0; i < data.length; i++){
  let docElement = {
     "docName": data[i].getAttribute("Title),
     "refDoc": getDoc(data[i].getAttribute("Title"))
 }
};
docArray.push(docElement);
...
console.log(docArray);
console.log(JSON.stringify(docArray));

getDocs function Javascript

function getDoc(document){
  var refDocs = [];
  $SP().list("listName").get({
    fields:"Title,Parent",
    where:'Title ="'+document+'"',
    }, function(data){
      for(let i = 0; i < data.length; i++){
        refdocs.push(data[i].getAttribute("Parent"));
      }
    });
   return refdocs;
}

I do have a similar project that creates an array in the same fashion though that array does not have a problem being stringified. I have attached pictures below for the console.log outputs of that array.

console.log(array) - working screenshot

console.log(JSON.stringify(array)) - working JSON.stringify

Any help would be greatly appreciated, thank you!

标签: javascriptarraysjson

解决方案


推荐阅读