enhancing objects by incorporating functions derived from JSON responses

Recently, I received a set of user data from a JSON server response. Below is an example of the data:

var users = [
    {id: 1, name: 'john', surname: 'smith'},
    {id: 2, name: 'john', surname: 'smith'},
    {id: 3, name: 'john', surname: 'smith'},
    {id: 4, name: 'john', surname: 'smith'},
    {id: 5, name: 'john', surname: 'smith'},
    {id: 6, name: 'john', surname: 'smith'},
    {id: 7, name: 'john', surname: 'smith'}
];

Throughout the application's business logic and templates (using handlebars), there is a need to have the full name of each user without repeatedly using the string concatenation logic name + ' ' + surname.

To address this, I have implemented the following enhancement for these users by adding a custom function:

for(var i=0; length=users.length; i<length; i++) {
    users[i].getFullName = function() {
        return this.name + ' ' + this.surname;
    }
}

Although this technique serves its purpose, some questions arise:

  • Is there a more efficient way to achieve this? The objective is to find a solution that follows an object-oriented style rather than using something like getFullNameOfUser(user).
  • While I can evaluate the time penalty of adding functions to all objects, how can I measure the memory impact of this approach? Methods such as JavaScript object size do not include functions in their calculations.

Answer №1

To enhance your code, consider creating a Users class and incorporating a method called getFullNameOfUser within its prototype.

var User = function(obj){
   this.id = obj.id;
   this.name = obj.name;
   this.surname = obj.surname;
};

User.prototype.getFullNameOfUser = function(){
   return this.name + ' ' + this.surname;
};

for(var i=0,length=users.length; i<length; i++) {
    users[i] = new User(users[i]);
}

In response to your query in the comment section, you can also try:

var User = function(obj){
       for(var key in obj){
          this[key]  = obj[key];
       }
    };

It's worth noting that using this approach may lead to unintended properties being added to the object.

Answer №2

It appears there might be a more efficient way to approach this, as attaching a function to every user can lead to unnecessary overhead.

By leveraging handlebars.js, you have the capability to manage concatenation directly in the view with ease:

<h2>Greetings {{user.firstName}} {{user.lastName}}!</h2>

Answer №3

If you find yourself in a situation where you need to perform repetitive tasks, one approach is to create utility functions that can be easily called with a specific context.

function generateGreeting () {
   return this.greeting + ', ' + this.name + '!';
};

generateGreeting.call(person[0]);

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

Are there any other benefits to utilizing the Decorator pattern besides enhancing dynamic behavior?

Currently, I am diving into the intricacies of the Decorator design pattern and a particular thought has been nagging at me. What if we simply had one base class with boolean values representing its features? Consider this example: Imagine a textview tha ...

Angular's lazy evaluation technique for single-shot binding on expressions

Since AngularJS version 1.3.0-beta.10, a new feature has been introduced called the "lazy one-time binding". To implement this feature, you can prefix simple expressions with ::, which instructs AngularJS to stop watching the expression after it has been ...

Magento - when the page just can't take it anymore

I've encountered a problem with my Magento store. Half of the page is displayed and then it breaks. Here's the link to the page: When I check the page source, this is the code where it seems to break: <script type="text/javascript> ...

The StrongLoop ng-lb command encounters issues when utilizing the local-storage-connector

Hello Strongloop community, I have been experimenting with the local-storage data store example provided by loopback. It's working well and I can successfully create and retrieve files from the local file system (used as a data source) using the REST ...

Exploring the functionality of className using materialUI

Attempting to test whether my component has a specific class is proving challenging. This difficulty stems from the fact that the class is generated using MaterialUI. For instance, I am looking for a class named spinningIconCenter, but in reality, it appea ...

Encountering difficulty rendering information within React and Redux component

I'm having trouble displaying some placeholder data on my component, as nothing is showing up. When I console.log the expected output, I see [object Object]. I suspect there might be an issue with my actions, actionCreators, and reducers. #actions/t ...

Tips for enhancing the efficiency of your Node.js and Express.js code while steering clear of callback hell

One of the controllers in my application contains a method that is responsible for printing an array of URLs using the webshot package. Below is the code snippet in question: router.post('/capture', function (req, res, next) { //Check params ...

Tips on sending data with a unique identifier to the backend through a route parameter

Can anyone help me figure out how to send a message to a specific backend route parameter while passing the current ID? I'm not sure how to inform the system about this ID. Here's the Vuex action: postMessage({commit}, payload, id) { axios.pos ...

How to create a calendar selection input using PHP?

Before I start writing the code myself, I am searching to see if there is already a solution available or if someone has previously outsourced the code. Below is an example of my date selection: https://i.sstatic.net/KqIDH.png I want to create a feature ...

Tips for formatting result data when using FullCalendar's eventSources URL

I am looking to retrieve my event data for fullcalendar from a separate URL. I have been following the method mentioned here: https://fullcalendar.io/docs/eventSources $('#calendar').fullCalendar({ eventSources: [ '/feed1.php' ...

Secure your desktop application with OAuth by enabling HTTPS on localhost

I am currently in the process of developing a desktop application that integrates with Spotify's oauth api using the implicit grant flow as outlined here: My plan is to incorporate an "Authenticate" button, which when clicked will open the user' ...

Unable to activate the navbar toggle feature on Bootstrap 4.0

****I have started working with bootstrap 4.0, but I am facing issues with the navbar toggle functionality. Even after trying to copy code from the official documentation and using the current alpha version of bootstrap, the toggle is not working as expe ...

Create a unique JSON list that supports polymorphism

I have a /tags.json where i want to display a list of players and teams, using the following code which I have included in both the players and teams models. def token "#{id}_#{self.class.name}" end Tags controller def index @players = Player.all ...

Is there a way to ensure that all asynchronous functions have finished executing before assigning them to module.exports?

Currently, I am working on developing an app that generates routes based on data retrieved from a MongoDB database using Mongoose. Here is the current setup: var app = express(); var articleRoute = require('./article.js'); var Articles = requi ...

Using the onClick function to set attributes in React JS

I am currently working with 2 functions: addBookmark() and removeBookmark(). There is a variable called IsBookmarked that can be either true or false. In my JSX code related to bookmarks, it looks like this: {props.singleCompany.IsBookmarked ? ( ...

Encountering a problem with AngularJS - receiving the [ng:areq] error, for more information visit http://errors.angularjs.org/1.3.2/ng/areq

While working on my CRUD angularApp, I encountered a strange error in Chrome dev tools. Here is the complete error message: error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=DbController&p1=not%20a%20function%2C%20got%20string at angular.j ...

The function "onClick" within an external .js file is being referenced

Just starting to learn Javascript and experimenting with an onClick event for an image in an external .js file using the HTML tag. <script type="text/javascript" src="embed.js"> The code found in "embed.js" is as follows: var image1=new Image(); i ...

Is it possible to access a PHP variable from a different file in an HTML file?

Can someone help me with separating the javascript from this php file? I need to specify where the javascript should look for the php file, as currently it only executes within the php file. <?php date_default_timezone_set('Europe/London'); r ...

Arranging ng-grid by a hidden column

Imagine having an array of objects structured like this: { name: ... age: ... dept: ... } Now, if you want to display these objects in an ng-grid with only columns for name and age, you can set it up like this: columnDefs: [{field:'name' ...

What is the best method for aligning buttons in a row with all the other buttons?

I have been attempting to display two buttons, id="strength" and id="minion", when a certain button, id="expandButton", is clicked. I want these two buttons to be positioned on either side of the button that triggers their cre ...