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 ?

4
  • What does that mean to have eleDetailsTop[id] when id is not a number? Feb 5, 2016 at 20:26
  • If you log eleDetailsTop.length, you will see why. Feb 5, 2016 at 20:29
  • 1
    You made eleDetailsTop an array, yet you populate it as if it's an object literal. It looks as if you want the array to be associative which is technically prohibited.
    – zer00ne
    Feb 5, 2016 at 20:30
  • Thanks all ! I got it working Feb 5, 2016 at 20:49

2 Answers 2

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 = {};
6
  • Thanks, But I want the index using id Not with just j. The index should be a string like eleDetailsTop['ele2'].. Is that possible ? Feb 5, 2016 at 20:31
  • 1
    @TharinduLucky then declare var eleDetailsTop = {};as an object. Feb 5, 2016 at 20:31
  • Thanks! I din't know that :) Anyway, I declare the object like you said, but the error still looks same.. :( Feb 5, 2016 at 20:41
  • 1
    @TharinduLucky works here: jsfiddle.net/r4zh0tgt Feb 5, 2016 at 20:46
  • 1
    Yeah, my bad. It's working :) Thanks all :) Feb 5, 2016 at 20:49
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>
2
  • 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. Feb 5, 2016 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 5, 2016 at 20:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.