I'm facing a situation in my application where I have a JSON object structured like this:
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 file
and url
properties can be easily derived from the key itself. Currently, I define the object in this way:
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;
}
Adding these derived properties to the object feels redundant. Yet, passing around the value instead of the key makes it necessary to include them. One possible solution would be:
var pages = {
home: {
title: "Home",
description: "The home page"
},
blog: {
title: "Blog",
description: "Our blog"
}
};
$.each(pages, function(key, value) {
value.jsonKey = key;
}
Having three different approaches, I'm not fully satisfied with any of them. I believe this is a common issue in programming. How do you usually tackle this problem, especially when the derived attribute is required in multiple instances?