I have an array like this:
var d = new Array();
d[0] = new Array();
d[0]['item1'] = '123';
d[0]['item2'] = '456';
d[0]['item3'] = '789';
d[1] = new Array();
d[1]['item1'] = '123';
d[1]['item2'] = '456';
d[1]['item3'] = '789';
When using console.log(JSON.stringify(d)); my console logs "[[],[]]"
Why does JSON.stringify() give an empty result?
Here's a jsFiddle showing my current situation
I read this. The answer is a solution, however my attribute names are variable, as you can see in the jsFiddle. Is there a way to make an attribute's name variable? Like this (doesn't work obviously):
var s = 'attrName';
var object = {
s: '123'
}// The object should have an attribute named attrName
Try:
d[0] = {};
instead of:
d[0] = new Array();
This way d[0] is an object and not an array.
Working example: http://jsfiddle.net/FLDfR/
This is happening because you are confusing arrays and objects.
While it is true that in JavaScript, arrays are just special objects but they are treated somewhat differently.
While this isn't technically true, pretend that arrays can only take integer keys, between 0 and 2^53.
// Tested in the console.
var d = [];
d[0] ={};
d[0]['item1'] = '123';
d[0]['item2'] = '456';
d[0]['item3'] = '789';
d[1] = {};
d[1]['item1'] = '123';
d[1]['item2'] = '456';
d[1]['item3'] = '789';
alert(JSON.stringify(d));
will do what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With