Array of Array, JSON.stringify() giving empty array instead of entire object

后端 未结 4 1187
后悔当初
后悔当初 2020-12-17 02:26

Here\'s my array (from Chrome console):

\"array

Here\'s the pertinent part of code:

4条回答
  •  余生分开走
    2020-12-17 03:05

    Here is the minimal amount of javascript to reproduce the issue

    var test = [];
    test["11h30"] = "15h00"
    test["18h30"] = "21h30"
    console.log(test);    
    console.log(JSON.stringify(test)); // outputs []
    

    The issue with the above is that, while javascript will be happy to let you late-bind new properties onto Array, JSON.stringify() will only attempt to serialize the actual elements in the array.

    A minimal change to make the object an actual object, and JSON.stringify works as expected:

    var test = {}; // here is thre only change. new array ([]) becomes new object ({})
    test["11h30"] = "15h00"
    test["18h30"] = "21h30"
    console.log(test);
    console.log(JSON.stringify(test)); // outputs {"11h30":"15h00","18h30":"21h30"}
    

提交回复
热议问题