masSdev masSdev - 2 months ago 35
AngularJS Question

Creating map object angular js

I have a map

daySubjects
and
subject
array i also have
days
array to store '
Sunday to Saturday
'
i have to create json like this using these variables

{
"daySubjects": {
"MONDAY": {
"subject": [

]
},
"TUESDAY": {
"subject": [

]
},
"WEDNESDAY": {
"subject": [

]
},
"THURSDAY": {
"subject": [

]
},
"FRIDAY": {
"subject": [

]
},
"SATURDAY": {
"subject": [

]
},
"SUNDAY": {
"subject": [

]
}
}


}

Answer

Ok, if I understand the qustion correctly, here is the sample plain javascript code:

var days = ["sun","mon","tue","wed","thu","fri","sat"];
var result = {
    daySubjects : {}
};
days.forEach(
    function(i){ 
        result.daySubjects[i] = { subject:[] };
    }
);

After execution this lines, result object will contain:

{
    "daySubjects": {
        "sun": {
            "subject": []
        },
        "mon": {
            "subject": []
        },
        "tue": {
            "subject": []
        },
        "wed": {
            "subject": []
        },
        "thu": {
            "subject": []
        },
        "fri": {
            "subject": []
        },
        "sat": {
            "subject": []
        }
    }
}

In javascript, you have to take care that objects that you are referring to, are defined. For example:

var test = {};

// fails because test.x is not defined
test.x[0] = 10;

//works cause you create array object before using it
test.x = [];
test.x[0] = 10;

What makes it easier, however, is that you can define a the whole nested JSON object structure in one go.

Comments