0

I'm creating a JS object like this

var eleDetailsTop = new Array();

var j = 0;
var id = "ele"+j;
eleDetailsTop[id] = {id: id, size : "40%", sizeLabel : 12, type : "image", title : "Image"};

Now, I'm trying to convert this object to a JSON...

var fields = JSON.stringify(eleDetailsTop);

So, my problem is, this only gives an empty result.

Here is what I got when I debugged with FireBug

enter image description here

As you can see there is another object called wrappedJSobject inside this. If you checked inside it, you can see another wrappedJSobject as so on...

Why is this ? Why is this weird ?

Community
  • 1
  • 1
Tharindu Thisarasinghe
  • 3,846
  • 8
  • 39
  • 70

2 Answers2

1

You're creating an array and assigning it alphanumeric property. Try this:

var j = 0;
var id = "ele"+j;
eleDetailsTop[j] = {id: id, size : "40%", sizeLabel : 12, type : "image", title : "Image"};

EDIT: If you do want to use id as property - defined eleDetailsTop as object:

var eleDetailsTop = {};
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
1

If you do:

var eleDetailsTop = {};

Then you can assign properties like

eleDetailsTop[id] = {}

But if you really need the array... that won't work because there's no associative arrays in js technically (they're objects).

<script>

    var test = {};

    test['iam1234'] = {};

    console.log(test);

</script>
dmgig
  • 4,400
  • 5
  • 36
  • 47
  • Define "work". It's absolutely possible to assign arbitrary properties to arrays, but you won't be able to include those properties when converted to JSON. – Felix Kling Feb 05 '16 at 20:42
  • By "work", I was thinking he wouldn't be able to use Array methods like forEach, but You are absolutely correct, it does "work" like a normal array (aside from the JSON issue). – dmgig Feb 05 '16 at 20:49