0

I have recently gotten into javascript (about four days ago), and I'm having troubles acclimating to the syntax a little bit. I'm creating a calender of sorts and I'm trying to get an array of objects (one for each month) to be declared within my "main" object, the calender. I have done copious amounts of googling and browsed all over W3Schools and can't seem to figure it out. So if I have

var calender = {
:
:...functions{},
months: [],

How would I go about getting objects inside of months and declaring their properties (i.e. months[0] would have a name of "January" and its number of days etc)? I am at a conceptual standstill. Do I accomplish this index by index, or can I just literally declare the objects at array creation? From what I grasped so far, it would seem normally I could just say something like var arr = {varName: "name",...(and so on)}, but it seems doing that in the brackets is not allowed, and I'm not sure syntactically where I access the indices. Or maybe I'm just doing this utterly bass ackwards. Any guidance would be greatly appreciated. Thanks

2 Answers 2

2

One way; object literals within an array:

var calendar = {

    months: [
        {
            name : "Jan",
            days : 31
        },
        {
            name : "Feb",
            days : "28ish"
        }  
    ]
};

alert( calendar.months[0].days );
Sign up to request clarification or add additional context in comments.

4 Comments

This is exactly what I was trying to do! Thank you. So basically the indices serve as the var name in a sense? Or is it bad to view it in that way?
Best to view them as key/value pairs. calendar has one key month that has an array as its value. In turn that array has two objects each of which have name and days values.
Kind of, (IMO) you should think of an Array (months) as a single entity (a variable, or in the example above the property of an object) that is a list containing values that are stored & accessed by a numeric index
Thank you both, having a conceptual understanding helps a great deal. Coming from other OOPs that I am also learning, its good to understand the distinctions. Appreciate your time =)
1

Let's get back to basics, this is how you can write literal objects, arrays and objects containing arrays containing objects that contain arrays:

var my_object = {key1: "value1", key2: "value2"};
console.log(my_object.key1);

var my_array = ["value1", "value2"];
console.log(my_array[0]);

var my_compound = {a: [{b: "c", d: [0, 1, 2]},
                       {b: "e", d: [3, 4, 5]}]};
console.log(my_compound.a[1].d[0]);  // => 3
console.log(my_compound["a"][1]["d"][0]);  // same thing, perhaps more readable?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.