0

Within a loop, I create the following object, which is then added to a global array:

i++;
var objToAdd = {"code1":myvar1, "code2":myvar2, "code3":myvar3};
ary.push(objToAdd);

However, this adds a keyless object to the array, like so:

{...
{"code1":"blah", "code2":"blah", "code3":"blah"},
{"code1":"blah", "code2":"blah", "code3":"blah"},
{"code1":"blah", "code2":"blah", "code3":"blah"},
...}

And by using i, in the loop, I'd like to add the object keyvalue pair, like so:

{...
"1":{"code1":"blah", "code2":"blah", "code3":"blah"},
"2":{"code1":"blah", "code2":"blah", "code3":"blah"},
"3":{"code1":"blah", "code2":"blah", "code3":"blah"},
...}

Many thanks.

Jammo
  • 1,838
  • 4
  • 25
  • 39
  • {} is not an array, it's an object – George Kagan Nov 04 '16 at 18:51
  • `[]` are 0-based arrays and `{}` are objects with string keys. Choose one: `[a, b, c]` or `{"1": a, "2": b, "3": c}`. You can't have it both ways. – user229044 Nov 04 '16 at 18:53
  • Not a duplicate of the linked question. Also, question edited. The `[]` and `{}` was the wrong way around, so removed from question as it doesn't apply. I need it `{{"1":{"code1":"blah"...},{},{}}` etc – Jammo Nov 04 '16 at 18:59
  • If you actually boil your question down to a simpler form, it might not be a duplicate. As it stands, you've asked for us to write a bunch of code for you without explaining which part of the problem is actually blocking you from proceeding. The simplest part that *I* can see is that you don't know how to use the variable `i` to define properties `"1"`, `"2"`, `"3"`, etc on an object. The question I closed this as a duplicate of will show you how to do this. – user229044 Nov 05 '16 at 14:45
  • Also, `{}.push` is not a real thing. It definitely will *not* produce the output you claim it does. `{{a:b}}` is not valid JavaScript or JSON. Again, `{}` denotes an object literal and it contains key/value pairs, not just values. There is no such thing as adding a "keyless object to the array", as there is no *array* anywhere in your question. – user229044 Nov 05 '16 at 14:47

0 Answers0