Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringify with multidimensional array gives empty result

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
like image 269
RobinvdA Avatar asked Nov 24 '25 19:11

RobinvdA


2 Answers

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/

like image 166
CD.. Avatar answered Nov 26 '25 09:11

CD..


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.

like image 30
Jeremy J Starcher Avatar answered Nov 26 '25 08:11

Jeremy J Starcher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!