Navigating attributes originating from the key in JSON: A guide to effective management

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?

Answer №1

Consider storing pages as a collection of objects rather than a single object with properties. This approach offers better logical consistency and addresses concerns about redundancy.

let pages = [
    {
        id: 'home'
        title: "Home",
        content: "The main page",
    },
    {
        id: 'blog',
        title: "Blog",
        content: "Explore our blog posts",
    }
];

Furthermore, you can define classes for page objects and implement methods that calculate derived properties (perhaps caching them for efficient repeated access). However, for simple string manipulations, this may be considered unnecessary.

Answer №2

What is the benefit of duplicating data in another format when you already have it in one form (your key)? In my view, it's unnecessary to choose either option, as you can always retrieve the file and url for a specific page directly from the page.key.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

What's the best way to retrieve a specific key value from a JSON array and store it in a variable to use for labeling purposes?

In my code, I have an array filled with JSON data. rows4 = [dict objectForKey:@"users"]; I am trying to extract a specific value from this array using the following line: NSString *hotelname = (NSString *) [rows4 valueForKey:@"H_NAME"]; After that, I w ...

Discover siblings in React component siblings

Creating a parent element (Board) that generates a list of children and provides a method to access this list can be done like so: export default class Board extends React.Component { constructor(props) { super(props); this.getList = t ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...

What is the method to retrieve the class name of an element when the div is created as '<div id 'one' class="element one"></div>'?

I have three elements named one, two, and three, declared as seen below: <div id =container> <div id 'one' class="element one"></div> <div id 'two' class="element two"></div> < ...

The validations continue to function properly even when HTML has been removed

In my form, I have implemented an "addmore" functionality that allows users to dynamically add a set of HTML input fields. Users can also remove the added rows if needed. While everything is functioning correctly, I am encountering an issue where validatio ...

Dynamically load modules within an AngularJS application

Is there a way to dynamically load module scripts? I have 2 JS files: module1.js (function() { var mod = angular.module('module1', []); .... })(); This is the second one: module2.js (function() { var mod = angular.module('m ...

Is it possible to use a shell script to replace the external CSS file link in an HTML file with the actual content of the CSS file

Seeking a solution for replacing external CSS and JS file links in an HTML document with the actual content of these files. The current structure of the HTML file is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C ...

Avoiding Duplicate Form Submissions Without JavaScript

Currently, I am working on a project where I am implementing the MVC pattern. Upon successful submission of a form, I redirect the user and display a flash message indicating success using session data. Users face no issues when using the back button or re ...

What is the hexadecimal color code for a specific element's background?

How can I retrieve the background color code of a specified element? var backgroundColor = $(".element").css("background-color"); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="elemen ...

Sort and extract different levels of keys from highly intricate nested JSON data

Issue I am faced with the task of extracting the id, name, and preview image from a list of YouTube videos. I am utilizing youtube-dl to obtain a json output, which I then analyze for the keys id, title, and the nested array thumbnails. Data Entry For an ...

What is the best way to retrieve "Results" data from a JSON file in order to perform calculations using NumPy?

Just beginning my Python journey with Boto3, working on parsing a JSON file: Student = [{"Student_ID": 1, "Name":"Erik", "ExamSubject": "English", "Result": "72.3", "ExamDate": "9/12/2020", "Gender": "M"}, {"Student_ID": 2, ...

Exploring ngModel components with a specified class

In my HTML code, I've assigned many elements with ngModel defined as ng-model = "object.[something]". For example: <div class="form-group row" ng-model="object.askUser"> I use this method to keep my purpose clear for these elements. My questi ...

Is there a way to schedule a function to run every 6 hours in node.js based on actual time instead of the device's time?

var currentTime = new Date().getHours(); if(currentTime == 6){ //function Do stuff } if(currentTime == 12){ //function Do stuff } if(currentTime == 18){ //function Do stuff } if(currentTime == 24){ //function ...

Difficulty surfaced in the React project following relocation to a different device

I'm new to using React and webpack with babel loader in my app. My project was running smoothly until I changed machines. I copied all the files except for node_modules (which I installed with npm install). Now, when I try to run or build the projec ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

Adjust the size of images using jQuery to perfectly fit the container dimensions

I am currently working on a script to automatically resize images that are too large for the container: $('img').each(function(i){ var parent_width = parseInt($(this).parent().width()), image_width = parseInt($(this).width()); ...

HTML integration of JavaScript not working as expected

My experience with separating files in HTML and JS has been positive - everything works smoothly when I link the JS file to the HTML. However, an issue arises when I decide to include the JS code directly within <script> tags in the HTML itself. The ...

Nodejs cookie settings

I am currently working on a small petition project and I want to implement a feature where a user who signs the petition will have a cookie set so that when they try to access the page again, they are redirected to a "thanks page". If the user has not sign ...