Using a Javascript object’s own fields in object literals

Feedback


Question:

My intention is to produce a solitary entity that comprises the entire configuration for a particular component. My preference is for it to be structured in the following manner:

var ObjectConfig = {
    fieldKeys : {
        name: "Obj. name",
        state: "Obj. state",
        color: "Obj. color"
    },
    templates : {
        basicTemplate :  [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.state ],
        altTemplate : [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.color ]
    }
}

What is the correct approach to achieve my goal if this method is not effective?

Apologies for the syntax errors in my previous message, I was in a hurry and wrote it by hand. Now that I have corrected it, I still face an issue with the error message:

Uncaught TypeError: Cannot read property 'fieldKeys' of undefined

. It seems that this approach is not feasible. Can you suggest a better alternative?


Solution:

The issue is that the literal constructs the object before assigning it to the

ObjectConfig

variable. This causes an error when trying to access

ObjectConfig.fieldKeys

inside the literal.

The optimal approach would be to initially create a single object and subsequently include additional attributes one by one.

var ObjectConfig = {
    fieldKeys: {
        name: "Obj. name",
        state: "Obj. state",
        color: "Obj. color"
    }
};
ObjectConfig.templates = {
    basicTemplate:  [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.state ],
    altTemplate: [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.color ]
};

A briefer approach would involve creating an additional variable for the keys object, which is assigned prior to building the templates object.

var keys, ObjectConfig = {
    fieldKeys: keys = {
        name: "Obj. name",
        state: "Obj. state",
        color: "Obj. color"
    },
    templates: {
        basicTemplate: [ keys.name, keys.state ],
        altTemplate: [ keys.name, keys.color ]
    }
};

In order to avoid having an extra variable in the global scope, an Immediately Invoked Function Expression (IIFE) can be utilized. This can result in a more legible code, such as the following example:

var ObjectConfig = (function() {
    var keys = {
        name: "Obj. name",
        state: "Obj. state",
        color: "Obj. color"
    };
    return {
        fieldKeys: keys,
        templates: {
            basicTemplate: [ keys.name, keys.state ],
            altTemplate: [ keys.name, keys.color ]
        }
    };
})();

Frequently Asked Questions