Question

I have a JSON object like this in my application:

var pages = {
    home: {
        title: "Home",
        description: "The home page",
        file: "home.html",
        url: "/home"
    },
    blog: {
        title: "Blog",
        description: "Our blog",
        file: "blog.html",
        url: "/blog"
    }
};

The properties file and url can always be derived from the respective key, so I currently define the above object like this in my code:

var pages = {
    home: {
        title: "Home",
        description: "The home page"
    },
    blog: {
        title: "Blog",
        description: "Our blog"
    }
};

$.each(pages, function(key, value) {
    value.file = key + ".html";
    value.url = "/" + key;
}

However, since file and url are derived attributes, adding them to the object seems redundant. But since I pass the value around for each page, not the key, I would have to add it to the object as well, which would also be redundant. Like this:

var pages = {
    home: {
        title: "Home",
        description: "The home page"
    },
    blog: {
        title: "Blog",
        description: "Our blog"
    }
};

$.each(pages, function(key, value) {
    value.jsonKey = key;
}

Now I have three different approaches and don't really like any of those. I think this should be a fairly common problem, so how would you approach this? And what if the derived attribute is to be used more than once?

Was it helpful?

Solution

you should consider storing pages as a list of objects rather than as an object with properties. This seems more consistent logically and solves your redundancy concerns.

var pages = [
    {
        key: 'home'
        title: "Home",
        description: "The home page",
    },
    {
        key: 'blog',
        title: "Blog",
        description: "Our blog",
    }
];

additionally. you can create classes for page objects and use methods that compute the derived properties (optionally caching them, in case you think repeated access is costly. However, doing that for simple string concatenation seems like an overkill)

OTHER TIPS

Why do you want to store the same data in a different form, when you already have it in one form(your key).
In my opinion, don't go for any of these, because whenever you wish to get the file and url for a particular page, you can easily get it from the page.key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top