0

I have the following javascript code:

var eventItems = {
        "addevent": { name: "Add New Event" },
        "addtodo": { name: "Add New Todo" }
    };
console.log(eventItems);

How can I create the eventItems object dynamically? I've tried this, and it doesn't work.

var eventItems = [];
eventItems.push({ "addevent": { name: "Add New Event" } });
eventItems.push({ "addtodo": { name: "Add New Todo" } });
console.log(eventItems);

I realize the first statement isn't an array, but I'm not sure of the syntax to add these 2 elements dynamically one at a time. Edited: modified question to clarify what I'm trying to do.

Huangism
  • 16,278
  • 7
  • 48
  • 74
Scottie
  • 11,050
  • 19
  • 68
  • 109
  • 1
    You say you want to make an **array**, so the second piece of code is correct. The first piece of code involves an object that's not an array. – Pointy Jul 23 '14 at 19:31
  • try `console.log(eventItems.toString());` It will output your array in text format on the console you will than probably be able to read the value of each items. Or you could do `console.log(JSON.stringify(eventItems));` this should help you debug what is going on or at least give you a clue. because the output of your console that you post here is perfectly normal. -EDIT- the console output was remove from the post. – Sebastien Jul 23 '14 at 19:36
  • I updated the question to make it more clear – Scottie Jul 23 '14 at 19:37
  • Still doesn't make much sense to me... What is the problem? this code should work, no??? – Sebastien Jul 23 '14 at 19:39
  • Yeah, I thought so too, but it doesn't. The first is not an array, but I don't know how to dynamically add elements without making it an array. – Scottie Jul 23 '14 at 19:40
  • Here is a jsBin of your code, it indeed works http://jsbin.com/devote/1/edit?js,console – Stevo Perisic Jul 23 '14 at 19:41
  • I think I know! try removing the double quotes exemple : `{ addevent: { name: "Add New Event" } }` – Sebastien Jul 23 '14 at 19:42
  • 1
    @Scottie: What do you want your output to look like? Can you show us what you are trying to create in the end? Do you just simply want to do this? `var eventItems = {}; eventItems['addevent'] = { name: "Add New Event" };`? – gen_Eric Jul 23 '14 at 19:43
  • On the first example, my console.log is showing "Object {addevent: Object, addtodo: Object}" The second is showing: [Object, Object]. I want the second to look exactly like the first. Removing the quotes didn't work. – Scottie Jul 23 '14 at 19:46
  • @Rocket Hazmat YES!! That's exactly what I was after!! That worked perfectly! Copy as an answer and I'll accept. Thank you! – Scottie Jul 23 '14 at 19:48

0 Answers0