JSON.Stringify Doesn't Work with Normal JavaScript Array

JSON.stringify doesn't work with normal Javascript array

JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.

The JSON array data type cannot have named keys on an array.

When you pass a JavaScript array to JSON.stringify the named properties will be ignored.

If you want named properties, use an Object, not an Array.

const test = {}; // Objecttest.a = 'test';test.b = []; // Arraytest.b.push('item');test.b.push('item2');test.b.push('item3');test.b.item4 = "A value"; // Ignored by JSON.stringifyconst json = JSON.stringify(test);console.log(json);

Why doesn't JSON.stringify include array in output JSON object?

The property you made is non enumerable. Set enumerable: true in the descriptor and it'll work.

var obj = {};var arr = [];arr.push(1, 2);console.log(arr); // 1,2Object.defineProperty(obj, "name", {  value: arr,  enumerable: true,});console.log(obj.name); // 1,2console.log(JSON.stringify(obj)); // {}

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

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"}

Why JSON.stringify() don't work correctly

You are attempting to use a 'sparse array' to store your data. Arrays do not have a clear way to be instantiated with elements at a specified index.

An object (or a Map) would suit your requirements better. To use an object, I modified your 'accounts' initation code that was commented:

// replace this:
dataObj["accounts"] = [];
// with this:
dataObj["accounts"] = {};

The other code you are using (e.g. accessing elements using the square brackets) will work the same. You should probably make the same adjustments to the other arrays you are using.

Sparse arrays can get ugly in some notations if you have large blank spaces (which your UUID methodology would certainly have). An object or a Map will not suffer that shortcoming.

An example of similar code, using objects instead of arrays:

let dataObj = {};
dataObj["accounts"] = {};
let uuid = 'abcdefghij12344';
dataObj["accounts"][uuid] = {}
dataObj["accounts"][uuid]['active'] = true;
dataObj["accounts"][uuid]['someotherval'] = true;

console.log(dataObj);
//outputs:

{ accounts: { abcdefghij12344: { active: true, someotherval: true } } }

let stringified = JSON.stringify(dataObj);
console.log(stringified);

// Outputs:
{"accounts":{"abcdefghij12344":{"active":true,"someotherval":true}}}

let parsed = JSON.parse(stringified);
console.log(parsed);

//Outputs:
{ accounts: { abcdefghij12344: { active: true, someotherval: true } } }

JSON.stringify not working when comparing two arrays

You can use JSON.stringify like this:

var arraya = [1,1,1];var arrayb = [2,2,2];
function isSolved(a, b) { return JSON.stringify(a) === JSON.stringify(b) ? "draw" : false;};
var input = [[1,1,1], [1,2,2], [2,2,2]];
for (var item of input) { console.log(isSolved(item, arraya)); console.log(isSolved(item, arrayb)); console.log("=====");}


Related Topics



Leave a reply



Submit